mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
merge dev into feat/postgres-support
This commit is contained in:
@@ -24,7 +24,7 @@ import { NotificationsModule } from '../../src/nest/notifications/notifications.
|
||||
import { OidcModule } from '../../src/nest/oidc/oidc.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { SettingsModule } from '../../src/nest/settings/settings.module';
|
||||
import { countRows, findRow, insertRow } from '../helpers/factories/rows';
|
||||
import { countRows, findRow, insertRow, updateRows } from '../helpers/factories/rows';
|
||||
import { readAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
@@ -262,6 +262,27 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('DELETE /users/:id/sso clears the stored SSO identity, audits it, and is admin-only (#3065)', async () => {
|
||||
const { user } = await makeUser(orm, { email: 'sso-moved@example.test', username: 'sso-moved' });
|
||||
await updateRows(orm, Users, { id: user.id }, { oidc_sub: 'sub-old', oidc_issuer: 'https://idp.example.test' });
|
||||
|
||||
const denied = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(2));
|
||||
expect(denied.status).toBe(403);
|
||||
|
||||
const res = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true, unlinked: true });
|
||||
const row = await findRow(orm, Users, { id: user.id });
|
||||
expect(row && { oidc_sub: row.oidc_sub ?? null, oidc_issuer: row.oidc_issuer ?? null }).toEqual({
|
||||
oidc_sub: null,
|
||||
oidc_issuer: null,
|
||||
});
|
||||
expect(await findRow(orm, AuditLog, { action: 'admin.user_sso_unlink', resource: String(user.id) })).not.toBeNull();
|
||||
|
||||
const self = await request(server).delete('/api/admin/users/1/sso').set('Cookie', sessionCookie(1));
|
||||
expect(self.status).toBe(400);
|
||||
});
|
||||
|
||||
it('404 on the dev-only test-notification outside development', async () => {
|
||||
const res = await request(server).post('/api/admin/dev/test-notification').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(404);
|
||||
|
||||
@@ -120,6 +120,28 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
|
||||
expect(res.body.permissions).toBeUndefined();
|
||||
});
|
||||
|
||||
it('PUT /app-settings oidc_auto_redirect reaches the public app-config the login page reads (#2925)', async () => {
|
||||
const admin = createUser(db as never, {
|
||||
username: 'redirect-admin',
|
||||
email: 'redirect-admin@example.test',
|
||||
role: 'admin',
|
||||
});
|
||||
const autoRedirect = async () => (await request(server).get('/api/auth/app-config')).body.oidc_auto_redirect;
|
||||
try {
|
||||
expect(await autoRedirect()).toBe(true);
|
||||
|
||||
const res = await request(server)
|
||||
.put('/api/auth/app-settings')
|
||||
.set('Cookie', sessionCookie(admin.user.id))
|
||||
.send({ oidc_auto_redirect: false });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await readAppSetting(orm, 'oidc_auto_redirect')).toBe('false');
|
||||
expect(await autoRedirect()).toBe(false);
|
||||
} finally {
|
||||
await deleteRows(orm, AppSettings, { key: 'oidc_auto_redirect' });
|
||||
}
|
||||
});
|
||||
|
||||
it('GET /me requires a session (401 without a cookie)', async () => {
|
||||
expect((await request(server).get('/api/auth/me')).status).toBe(401);
|
||||
});
|
||||
|
||||
@@ -217,7 +217,9 @@ describe('Booking import e2e (#2477): a schema-bound provider on the upload rout
|
||||
expect(res.body.warnings[0]).toMatch(
|
||||
/^Incomplete LodgingReservation in Bestätigung_1234567890\.PDF\[0\] \(no reservationFor\)/,
|
||||
);
|
||||
expect(res.body.files).toEqual([{ fileName: 'Bestätigung_1234567890.PDF', aiAvailable: true, aiUsed: true }]);
|
||||
expect(res.body.files).toEqual([
|
||||
{ fileName: 'Bestätigung_1234567890.PDF', aiAvailable: true, aiUsed: true, outcome: 'ok' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('once Gemini fills the venue: one hotel in EUR, attached to the uploaded file', async () => {
|
||||
@@ -250,4 +252,34 @@ describe('Booking import e2e (#2477): a schema-bound provider on the upload rout
|
||||
expect(res.body.items[0].metadata.priceCurrency).toBe('EUR');
|
||||
expect(res.body.items[0].source.fileName).toBe('Bestätigung_2.pdf');
|
||||
});
|
||||
|
||||
it('confirm writes a referenced booking once: a second copy, in the same request or a later one, is a duplicate', async () => {
|
||||
const train = {
|
||||
type: 'train',
|
||||
title: 'ICE 123',
|
||||
confirmation_number: 'ab 12c',
|
||||
reservation_time: '2026-09-06T10:00',
|
||||
source: { fileName: 'ticket.pdf', index: 0 },
|
||||
};
|
||||
const confirm = (items: unknown[]) =>
|
||||
request(server)
|
||||
.post(`/api/trips/${tripId}/reservations/import/booking/confirm`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ items });
|
||||
|
||||
const first = await confirm([train, { ...train, confirmation_number: 'AB12C' }]);
|
||||
expect(first.status).toBe(201);
|
||||
expect(first.body.created).toHaveLength(1);
|
||||
expect(first.body.created[0]).toMatchObject({
|
||||
title: 'ICE 123',
|
||||
external_source: 'import',
|
||||
external_id: 'AB12C|train|2026-09-06|',
|
||||
sync_enabled: 0,
|
||||
});
|
||||
expect(first.body.failed).toEqual([{ index: 1, reason: 'duplicate' }]);
|
||||
|
||||
const again = await confirm([train]);
|
||||
expect(again.status).toBe(201);
|
||||
expect(again.body).toEqual({ created: [], failed: [{ index: 0, reason: 'duplicate' }] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
* called through a real MCP session on the whole app (buildApp, the real
|
||||
* registry with its addon and sub-feature gates, scopes and error mapper,
|
||||
* the real CollabService and a migrated temp SQLite), the way the
|
||||
* assistant's note cards read them.
|
||||
* assistant's note cards read them. The shared links (#3076) ride the same
|
||||
* path: saved over MCP, read back over MCP and over the REST route.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { makeCollabNote } from '../helpers/factories/collab';
|
||||
import { setAddonEnabled, setCollabFeature } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
@@ -17,6 +19,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
@@ -107,3 +110,39 @@ describe('the shared notes over MCP', () => {
|
||||
expect((await session(user.id, 'list_collab_notes', { tripId: trip.id })).answer).toEqual({ notes: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('the shared links over MCP', () => {
|
||||
it('COLLAB-MCP-E2E-004: saves a link the Links panel then lists, and reads it back', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'Lisbon' });
|
||||
const created = await session(user.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: 'Tram 28 timetable',
|
||||
url: 'https://example.com/tram-28',
|
||||
});
|
||||
const link = (created.answer as { link: Record<string, unknown> }).link;
|
||||
expect(link).toMatchObject({ title: 'Tram 28 timetable', url: 'https://example.com/tram-28', pinned: 0 });
|
||||
|
||||
const { answer } = await session(user.id, 'list_collab_links', { tripId: trip.id });
|
||||
expect(answer).toEqual({ links: [expect.objectContaining({ id: link.id, username: user.username })] });
|
||||
const rest = await request(app.getHttpServer())
|
||||
.get(`/api/trips/${trip.id}/collab/links`)
|
||||
.set('Cookie', authCookie(user.id));
|
||||
expect(rest.status).toBe(200);
|
||||
expect(rest.body.links.map((row: { id: number }) => row.id)).toEqual([link.id]);
|
||||
});
|
||||
|
||||
it('COLLAB-MCP-E2E-005: is gone while the links are switched off', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
await setCollabFeature(orm, 'links', false);
|
||||
try {
|
||||
const { offered } = await session(user.id, 'list_collab_links', { tripId: trip.id });
|
||||
expect(offered).not.toContain('list_collab_links');
|
||||
expect(offered).not.toContain('create_collab_link');
|
||||
expect(offered).toContain('list_collab_notes');
|
||||
} finally {
|
||||
await setCollabFeature(orm, 'links', true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,6 +208,66 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
|
||||
expect(await countRows(orm, CollectionPlaces, { collection: col.id })).toBe(0);
|
||||
});
|
||||
|
||||
// #2646: saving took the provider ids, website, phone and price while editing
|
||||
// did not, so fixing one meant deleting and re-saving the place, which lost its
|
||||
// labels, ratings, position and id.
|
||||
it('COLLECTIONS-E2E-091: PATCH sets and clears the provider ids, website, phone and price', async () => {
|
||||
const col = (
|
||||
await request(server)
|
||||
.post('/api/addons/collections')
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ name: 'Listings' })
|
||||
).body;
|
||||
const saved = await request(server)
|
||||
.post('/api/addons/collections/places')
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send({ collection_id: col.id, name: 'Septime', phone: '+33 1 43 67 38 29', price: 40, currency: 'EUR' });
|
||||
expect(saved.status).toBe(200);
|
||||
const placeId = saved.body.place.id;
|
||||
const patch = (body: Record<string, unknown>) =>
|
||||
request(server)
|
||||
.patch(`/api/addons/collections/places/${placeId}`)
|
||||
.set('Cookie', sessionCookie(ownerId))
|
||||
.send(body);
|
||||
|
||||
const patched = await patch({
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: '0x47e6:0x1b2',
|
||||
osm_id: 'node/42',
|
||||
website: 'septime-charonne.fr',
|
||||
price: 55,
|
||||
});
|
||||
expect(patched.status).toBe(200);
|
||||
// A bare domain gets https:// as on save; what the update leaves out stays.
|
||||
expect(patched.body).toMatchObject({
|
||||
id: placeId,
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: '0x47e6:0x1b2',
|
||||
osm_id: 'node/42',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
price: 55,
|
||||
currency: 'EUR',
|
||||
});
|
||||
|
||||
const refused = await patch({ website: 'javascript:alert(1)' });
|
||||
expect(refused.status).toBe(400);
|
||||
expect(refused.body.error).toMatch(/^website: /);
|
||||
expect((await findRow(orm, CollectionPlaces, { id: placeId }))?.website).toBe('https://septime-charonne.fr');
|
||||
|
||||
const cleared = await patch({ website: null, phone: null, price: null, currency: null, google_place_id: null });
|
||||
expect(cleared.status).toBe(200);
|
||||
expect(await findRow(orm, CollectionPlaces, { id: placeId })).toMatchObject({
|
||||
website: null,
|
||||
phone: null,
|
||||
price: null,
|
||||
currency: null,
|
||||
google_place_id: null,
|
||||
google_ftid: '0x47e6:0x1b2',
|
||||
osm_id: 'node/42',
|
||||
});
|
||||
});
|
||||
|
||||
// Regression for #1437: editing a place (PATCH without a status field) must NOT
|
||||
// reset a 'want'/'visited' place back to 'idea'.
|
||||
it('COLLECTIONS-E2E-012: PATCH without status leaves the saved status unchanged', async () => {
|
||||
@@ -648,6 +708,37 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
|
||||
expect((await request(server).post('/api/addons/collections/gpx/read').send({ gpx: '<gpx/>' })).status).toBe(401);
|
||||
});
|
||||
|
||||
// ── KML for Google My Maps (#1866) ───────────────────────────────────────
|
||||
it('COLLECTIONS-E2E-092: a list goes out as KML pins, the places without coordinates counted', async () => {
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Rome' })).body;
|
||||
await request(server).post('/api/addons/collections/places').set(as(ownerId)).send({
|
||||
collection_id: col.id,
|
||||
name: 'Pinned',
|
||||
lat: 41.9,
|
||||
lng: 12.48,
|
||||
address: 'Via Nuova 1',
|
||||
status: 'revisit',
|
||||
});
|
||||
await request(server)
|
||||
.post('/api/addons/collections/places')
|
||||
.set(as(ownerId))
|
||||
.send({ collection_id: col.id, name: 'Vague' });
|
||||
|
||||
const exported = await request(server).get(`/api/addons/collections/${col.id}/export/kml`).set(as(ownerId));
|
||||
expect(exported.status).toBe(200);
|
||||
expect(exported.body).toMatchObject({ name: 'Rome', pins: 1, omitted: 1 });
|
||||
expect(exported.body.kml).toContain('<name>Pinned</name>');
|
||||
expect(exported.body.kml).toContain('<address>Via Nuova 1</address>');
|
||||
expect(exported.body.kml).toContain('<coordinates>12.48,41.9</coordinates>');
|
||||
expect(exported.body.kml).not.toContain('Vague');
|
||||
|
||||
// The same read as the list file: a list the caller cannot see has none.
|
||||
expect((await request(server).get(`/api/addons/collections/${col.id}/export/kml`).set(as(otherId))).status).toBe(
|
||||
404,
|
||||
);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-E2E-082: a list the caller cannot see has no GPX either', async () => {
|
||||
const col = (
|
||||
await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Mine' })
|
||||
|
||||
@@ -78,6 +78,7 @@ function makeClientStub() {
|
||||
listVisits: boom('listVisits'),
|
||||
listTracks: boom('listTracks'),
|
||||
listPoints: boom('listPoints'),
|
||||
listGeocodedPoints: boom('listGeocodedPoints'),
|
||||
listVisitedCities: boom('listVisitedCities'),
|
||||
findVisitsNear: boom('findVisitsNear'),
|
||||
};
|
||||
|
||||
@@ -62,6 +62,13 @@ let orm: TestOrm;
|
||||
|
||||
const BASE = 'https://trek.example.test';
|
||||
|
||||
/** The token at the end of a feed url, failing the case when the url has none. */
|
||||
function feedToken(url: string, kind: 'trip' | 'user'): string {
|
||||
const token = new RegExp(`${kind}/([0-9a-f-]+)[.]ics$`).exec(url)?.[1];
|
||||
if (!token) throw new Error(`no ${kind} feed token in ${url}`);
|
||||
return token;
|
||||
}
|
||||
|
||||
describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
@@ -153,7 +160,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
const { user: owner } = createUser(db);
|
||||
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'trip');
|
||||
expect((await request(server).get(`/api/feed/trip/${token}.ics`)).status).toBe(200);
|
||||
|
||||
const del = await request(server).delete(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
@@ -232,7 +239,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
const { user: member } = createUser(db);
|
||||
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'trip');
|
||||
addTripMember(db, trip.id, member.id);
|
||||
|
||||
// The member may no longer manage it, but existing subscriptions must not break.
|
||||
@@ -248,7 +255,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
const { user: owner } = createUser(db);
|
||||
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'trip');
|
||||
|
||||
const res = await request(server).get(`/api/feed/trip/${token}.ics`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -256,7 +263,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(res.text).toContain('REFRESH-INTERVAL;VALUE=DURATION:PT1H');
|
||||
expect(res.text).toContain('X-PUBLISHED-TTL:PT1H');
|
||||
expect(res.text).toContain('BEGIN:VEVENT');
|
||||
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id);
|
||||
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id, { dayEvents: true });
|
||||
});
|
||||
|
||||
// The @Public feed quoted cal.filename straight into Content-Disposition, so
|
||||
@@ -265,7 +272,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
const { user: owner } = createUser(db);
|
||||
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/trip\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'trip');
|
||||
|
||||
// ASCII parity first: the default sample calendar keeps the exact legacy header.
|
||||
const plain = await request(server).get(`/api/feed/trip/${token}.ics`);
|
||||
@@ -279,6 +286,17 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('public trip feed: days=0 asks the calendar for no per-day summaries (#2602)', async () => {
|
||||
const { user: owner } = createUser(db);
|
||||
const trip = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const gen = await request(server).post(`/api/trips/${trip.id}/feed/token`).set('Cookie', sessionCookie(owner.id));
|
||||
const token = feedToken(gen.body.feed_url, 'trip');
|
||||
|
||||
const res = await request(server).get(`/api/feed/trip/${token}.ics?days=0`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(buildTripCalendar).toHaveBeenCalledWith(trip.id, { dayEvents: false });
|
||||
});
|
||||
|
||||
it('public trip feed: 404 for an unknown token', async () => {
|
||||
const res = await request(server).get('/api/feed/trip/00000000-0000-0000-0000-000000000000.ics');
|
||||
expect(res.status).toBe(404);
|
||||
@@ -302,7 +320,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
createTrip(db, owner.id, { title: 'Old', start_date: '2000-01-01', end_date: '2000-01-10' });
|
||||
|
||||
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'user');
|
||||
|
||||
const res = await request(server).get(`/api/feed/user/${token}.ics`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -322,7 +340,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
addTripMember(db, shared.id, owner.id);
|
||||
|
||||
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'user');
|
||||
|
||||
const res = await request(server).get(`/api/feed/user/${token}.ics`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -331,6 +349,20 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(calledIds).toEqual([owned.id, shared.id].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it('all-trips feed: days=0 reaches the calendar of every trip (#2602)', async () => {
|
||||
const { user: owner } = createUser(db);
|
||||
const first = createTrip(db, owner.id, { start_date: '2026-01-01', end_date: '2099-01-01' });
|
||||
const second = createTrip(db, owner.id, { start_date: '2026-02-01', end_date: '2099-01-01' });
|
||||
|
||||
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
|
||||
const token = feedToken(gen.body.feed_url, 'user');
|
||||
|
||||
const res = await request(server).get(`/api/feed/user/${token}.ics?days=0`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(buildTripCalendar).toHaveBeenCalledWith(first.id, { dayEvents: false });
|
||||
expect(buildTripCalendar).toHaveBeenCalledWith(second.id, { dayEvents: false });
|
||||
});
|
||||
|
||||
it('public user feed: 404 for an unknown token', async () => {
|
||||
const res = await request(server).get('/api/feed/user/00000000-0000-0000-0000-000000000000.ics');
|
||||
expect(res.status).toBe(404);
|
||||
@@ -355,7 +387,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
}));
|
||||
|
||||
const gen = await request(server).post('/api/feed/user/token').set('Cookie', sessionCookie(owner.id));
|
||||
const token = gen.body.feed_url.match(/user\/([0-9a-f-]+)\.ics$/)![1];
|
||||
const token = feedToken(gen.body.feed_url, 'user');
|
||||
|
||||
const res = await request(server).get(`/api/feed/user/${token}.ics`);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
@@ -40,7 +40,8 @@ const { db } = vi.hoisted(() => {
|
||||
// (is_archived, reminder_days and the two timestamps); the real schema has all four.
|
||||
tmp.exec(`CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, currency TEXT,
|
||||
is_archived INTEGER DEFAULT 0, reminder_days INTEGER DEFAULT 3,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
costs_mode TEXT NOT NULL DEFAULT 'split');`);
|
||||
// TripAccessGuard now reads TripsRepository.findAccessible directly
|
||||
// (Plan 3c Task 0b), a real join against trip_members.
|
||||
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Live flight status e2e: GET /api/trips/:tripId/flights/live through the
|
||||
* real JwtAuthGuard and TripAccessGuard over a migrated snapshot db. The
|
||||
* read never asks a feed, so fetch is a spy that must stay unused; the
|
||||
* response contract is checked on every 200 (NODE_ENV=test).
|
||||
*/
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { AppConfigModule } from '../../src/nest/app-config/app-config.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { FlightLiveModule } from '../../src/nest/flight-live/flight-live.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
|
||||
import { deleteRows, insertRow } from '../helpers/factories/rows';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { tripFlightLiveResponseSchema } from '@trek/shared';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
|
||||
describe('Flight live e2e (real guards + snapshot SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let ownerId: number;
|
||||
let strangerId: number;
|
||||
let tripId: number;
|
||||
let flightId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
AppConfigModule,
|
||||
RealtimeModule,
|
||||
FlightLiveModule,
|
||||
],
|
||||
}).compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
const orm = app.get(MikroORM);
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
ownerId = owner.id;
|
||||
strangerId = stranger.id;
|
||||
tripId = (await makeTrip(orm, owner.id, { title: 'Japan' })).id;
|
||||
const flight = await makeReservation(orm, tripId, {
|
||||
title: 'FRA to HND',
|
||||
type: 'flight',
|
||||
metadata: JSON.stringify({ flight_number: 'LH 716', airline: 'Lufthansa' }),
|
||||
});
|
||||
flightId = flight.id;
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Frankfurt (FRA)',
|
||||
code: 'FRA',
|
||||
lat: 50.0333,
|
||||
lng: 8.5706,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2030-07-01',
|
||||
local_time: '13:40',
|
||||
});
|
||||
await makeReservationEndpoint(orm, flight.id, {
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Tokyo Haneda (HND)',
|
||||
code: 'HND',
|
||||
lat: 35.5523,
|
||||
lng: 139.7798,
|
||||
timezone: 'Asia/Tokyo',
|
||||
local_date: '2030-07-02',
|
||||
local_time: '08:15',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const url = (id: number = tripId) => `/api/trips/${id}/flights/live`;
|
||||
|
||||
it('FLE2E-001: 401 without a session cookie', async () => {
|
||||
const res = await request(server).get(url());
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('FLE2E-002: 404 "Trip not found" for a trip the caller cannot reach', async () => {
|
||||
const res = await request(server).get(url()).set('Cookie', sessionCookie(strangerId));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
});
|
||||
|
||||
it('FLE2E-003: 200 with every flight leg and its schedule in UTC, without asking a feed', async () => {
|
||||
const fetcher = vi.fn();
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
const res = await request(server).get(url()).set('Cookie', sessionCookie(ownerId));
|
||||
expect(res.status).toBe(200);
|
||||
expect(tripFlightLiveResponseSchema.parse(res.body)).toEqual(res.body);
|
||||
expect(res.body).toMatchObject({ enabled: true, attribution: 'Live positions: adsb.lol (ODbL)' });
|
||||
expect(res.body.flights).toEqual([
|
||||
expect.objectContaining({
|
||||
reservation_id: flightId,
|
||||
leg_index: 0,
|
||||
callsign: 'DLH716',
|
||||
flight_number: 'LH 716',
|
||||
service_date: '2030-07-01',
|
||||
origin: { code: 'FRA', name: 'Frankfurt', lat: 50.0333, lng: 8.5706, timezone: 'Europe/Berlin' },
|
||||
destination: { code: 'HND', name: 'Tokyo Haneda', lat: 35.5523, lng: 139.7798, timezone: 'Asia/Tokyo' },
|
||||
phase: 'scheduled',
|
||||
scheduled_departure: '2030-07-01T11:40:00.000Z',
|
||||
scheduled_arrival: '2030-07-01T23:15:00.000Z',
|
||||
position: null,
|
||||
source: null,
|
||||
}),
|
||||
]);
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FLE2E-004: switched off by the admin it answers enabled false and no flights', async () => {
|
||||
const orm = app.get(MikroORM);
|
||||
await insertRow(orm, AppSettings, { key: 'flight_live_enabled', value: 'false' });
|
||||
try {
|
||||
const res = await request(server).get(url()).set('Cookie', sessionCookie(ownerId));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ enabled: false, attribution: null, flights: [] });
|
||||
} finally {
|
||||
await deleteRows(orm, AppSettings, { key: 'flight_live_enabled' });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* /api/mail-ingest e2e: the real JwtAuthGuard, TripAccessGuard, AdminGuard,
|
||||
* Zod pipe, multer and response contracts over a snapshot SQLite, with
|
||||
* MailIngestModule's real repositories and services. Replaced: what reaches
|
||||
* outside (the AI reading, kitinerary, file storage, geocoding, the
|
||||
* notifications). A mail goes in by upload and by the signed webhook, is
|
||||
* read by the real pipeline, and is added, undone and refused through the
|
||||
* routes the client and the admin dialog use.
|
||||
*/
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { BookingImportService } from '../../src/nest/booking-import/booking-import.service';
|
||||
import { importExternalId } from '../../src/nest/booking-import/booking-origin';
|
||||
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { FilesService } from '../../src/nest/files/files.service';
|
||||
import { MailReadService } from '../../src/nest/llm-parse/mail-read.service';
|
||||
import { walkMail } from '../../src/nest/llm-parse/mime-walker';
|
||||
import { MailIngestProcessJob } from '../../src/nest/mail-ingest/mail-ingest-process.job';
|
||||
import { signWebhookMail } from '../../src/nest/mail-ingest/mail-ingest-webhook.service';
|
||||
import { MailIngestModule } from '../../src/nest/mail-ingest/mail-ingest.module';
|
||||
import { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { countRows } from '../helpers/factories/rows';
|
||||
import { setAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// A snapshot database of its own, handed to the ORM, the unit of work and the factories.
|
||||
const db = createSnapshotTestDb();
|
||||
|
||||
const USER = 1;
|
||||
const OTHER = 2;
|
||||
const ADMIN = 3;
|
||||
const SECRET = 'w'.repeat(40);
|
||||
const TEMPLATE = 'trek+{token}@mail.example.com';
|
||||
|
||||
/** A day `days` from today: the checks take a booking only within a few years of now. */
|
||||
const dayFromToday = (days: number) => new Date(Date.now() + days * 86_400_000).toISOString().slice(0, 10);
|
||||
const FLIGHT_DAY = dayFromToday(30);
|
||||
|
||||
const endpoint = (role: 'from' | 'to', name: string, code: string, lat: number, lng: number) => ({
|
||||
role,
|
||||
sequence: role === 'from' ? 0 : 1,
|
||||
name,
|
||||
code,
|
||||
lat,
|
||||
lng,
|
||||
timezone: null,
|
||||
local_time: null,
|
||||
local_date: null,
|
||||
});
|
||||
const FLIGHT: BookingImportPreviewItem = {
|
||||
type: 'flight',
|
||||
title: 'LH 716 Tokyo to Osaka',
|
||||
reservation_time: `${FLIGHT_DAY}T10:00`,
|
||||
reservation_end_time: `${FLIGHT_DAY}T11:15`,
|
||||
confirmation_number: 'ABC123',
|
||||
metadata: { flight_number: 'LH716' },
|
||||
endpoints: [
|
||||
endpoint('from', 'Tokyo Haneda', 'HND', 35.55, 139.78),
|
||||
endpoint('to', 'Osaka Itami', 'ITM', 34.78, 135.44),
|
||||
],
|
||||
source: { fileName: 'mail.eml', index: 0 },
|
||||
};
|
||||
|
||||
const bookingImport = {
|
||||
readMailBookings: vi.fn(async (): Promise<BookingImportPreviewItem[]> => [FLIGHT]),
|
||||
mapAiReservations: vi.fn(async (): Promise<BookingImportPreviewItem[]> => []),
|
||||
externalKey: (item: BookingImportPreviewItem) => importExternalId(item),
|
||||
};
|
||||
const reader = { walk: (raw: Buffer) => walkMail(raw), isAvailable: vi.fn(async () => false), read: vi.fn() };
|
||||
|
||||
function eml(id: string, to = 'trips@example.com'): Buffer {
|
||||
return Buffer.from(
|
||||
[
|
||||
'From: Mia <mia@example.com>',
|
||||
`To: ${to}`,
|
||||
'Subject: Fwd: Your flight LH 716',
|
||||
`Message-ID: <${id}@example.com>`,
|
||||
'Date: Mon, 1 Jan 2030 10:00:00 +0000',
|
||||
'Content-Type: text/plain; charset=utf-8',
|
||||
'',
|
||||
`Booking reference ABC123. Flight LH 716 from Tokyo to Osaka on ${FLIGHT_DAY}.`,
|
||||
].join('\r\n'),
|
||||
);
|
||||
}
|
||||
|
||||
describe('/api/mail-ingest e2e (real guards + snapshot SQLite)', () => {
|
||||
let orm: TestOrm;
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let tripId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), MailIngestModule],
|
||||
})
|
||||
.overrideProvider(BookingImportService)
|
||||
.useValue(bookingImport)
|
||||
.overrideProvider(MailReadService)
|
||||
.useValue(reader)
|
||||
.overrideProvider(FilesService)
|
||||
.useValue({ createFileFromBytes: vi.fn(async () => ({ id: 77 })), softDeleteFile: vi.fn() })
|
||||
.overrideProvider(MapsService)
|
||||
.useValue({ geocodeQuery: vi.fn(async () => null) })
|
||||
.overrideProvider(NotificationsService)
|
||||
.useValue({ send: vi.fn(async () => ({ attempted: 0, delivered: 0 })), registerResponseAction: vi.fn() })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
|
||||
/**
|
||||
* Runs the pipeline over what came in, the way its two-minute job does: the
|
||||
* cron registrar runs every tick in a request context of its own.
|
||||
*/
|
||||
const readQueued = () => withRequestContext(app.get(MikroORM), () => app.get(MailIngestProcessJob).tick());
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: USER, username: 'mia', email: 'mia@example.com' });
|
||||
await makeUser(orm, { id: OTHER, username: 'noa', email: 'noa@example.com' });
|
||||
await makeAdmin(orm, { id: ADMIN, username: 'admin', email: 'admin@example.com' });
|
||||
const dates = { start_date: dayFromToday(20), end_date: dayFromToday(40) };
|
||||
tripId = (await makeTrip(orm, USER, { title: 'Japan', ...dates })).id;
|
||||
await setAppSetting(orm, 'mail_ingest_enabled', 'true');
|
||||
await setAppSetting(orm, 'mail_ingest_address_template', TEMPLATE);
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('MAIL-E2E-001: 401 without a session on every route a person or an admin uses', async () => {
|
||||
const paths = ['/api/mail-ingest/settings', '/api/mail-ingest/inbox', '/api/admin/mail-ingest/status'];
|
||||
const answers = await Promise.all(paths.map((path) => request(server).get(path)));
|
||||
answers.forEach((answer, i) => expect(answer.status, paths[i]).toBe(401));
|
||||
expect((await request(server).post(`/api/trips/${tripId}/mail-ingest/address`)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('MAIL-E2E-002: the settings card, its switches and a renewed own address', async () => {
|
||||
const card = await request(server).get('/api/mail-ingest/settings').set(as(USER));
|
||||
expect(card.status).toBe(200);
|
||||
expect(card.body).toMatchObject({ available: true, ai_available: false, pending: 0 });
|
||||
// The first look makes the person's own address, so nobody has to ask for one before forwarding.
|
||||
const first = card.body.address.address as string;
|
||||
expect(first).toMatch(/^trek\+[a-z2-7]{24}@mail\.example\.com$/);
|
||||
const again = await request(server).get('/api/mail-ingest/settings').set(as(USER));
|
||||
expect(again.body.address.address).toBe(first);
|
||||
|
||||
expect((await request(server).patch('/api/mail-ingest/settings').set(as(USER)).send({})).status).toBe(400);
|
||||
const off = await request(server).patch('/api/mail-ingest/settings').set(as(USER)).send({ auto_add: false });
|
||||
expect(off.status).toBe(200);
|
||||
expect(off.body.prefs).toEqual({ enabled: true, ai_enabled: true, auto_add: false });
|
||||
|
||||
const renewed = await request(server).post('/api/mail-ingest/address/renew').set(as(USER));
|
||||
expect(renewed.status).toBe(200);
|
||||
expect(renewed.body.address.address).toMatch(/^trek\+[a-z2-7]{24}@mail\.example\.com$/);
|
||||
expect(renewed.body.address.address).not.toBe(first);
|
||||
});
|
||||
|
||||
it('MAIL-E2E-003: an uploaded mail waits in the inbox, is added by hand and undone, for its person', async () => {
|
||||
const soon = vi.spyOn(app.get(MailIngestProcessJob), 'runSoon');
|
||||
const upload = await request(server)
|
||||
.post('/api/mail-ingest/upload')
|
||||
.set(as(USER))
|
||||
.attach('file', eml('upload-1'), { filename: 'booking.eml', contentType: 'message/rfc822' });
|
||||
expect(upload.status).toBe(201);
|
||||
expect(upload.body).toMatchObject({ duplicate: false, message: { transport: 'upload', status: 'queued' } });
|
||||
expect(soon).toHaveBeenCalledTimes(1);
|
||||
soon.mockRestore();
|
||||
expect(await readQueued()).toBe(1);
|
||||
|
||||
const inbox = await request(server).get('/api/mail-ingest/inbox').set(as(USER));
|
||||
expect(inbox.status).toBe(200);
|
||||
expect(inbox.body.pending).toBe(1);
|
||||
const [entry] = inbox.body.entries;
|
||||
expect(entry).toMatchObject({ reason: 'ask_first', suggested_trip: { id: tripId, title: 'Japan' } });
|
||||
expect((await request(server).get('/api/mail-ingest/inbox/count').set(as(USER))).body).toEqual({ pending: 1 });
|
||||
|
||||
const apply = (userId: number) =>
|
||||
request(server).post(`/api/mail-ingest/candidates/${entry.id}/apply`).set(as(userId)).send({});
|
||||
expect((await apply(OTHER)).status).toBe(404);
|
||||
const applied = await apply(USER);
|
||||
expect(applied.status).toBe(200);
|
||||
expect(applied.body.candidate).toMatchObject({ resolution: 'applied', resolved_trip_id: tripId });
|
||||
expect(await countRows(orm, Reservations, { trip: tripId })).toBe(1);
|
||||
|
||||
const undone = await request(server).post(`/api/mail-ingest/candidates/${entry.id}/undo`).set(as(USER)).send({});
|
||||
expect(undone.status).toBe(200);
|
||||
expect(undone.body.candidate.resolution).toBe('undone');
|
||||
expect(await countRows(orm, Reservations, { trip: tripId })).toBe(0);
|
||||
|
||||
const preview = (userId: number) =>
|
||||
request(server).get(`/api/mail-ingest/messages/${entry.message_id}/preview`).set(as(userId));
|
||||
const shown = await preview(USER);
|
||||
expect(shown.status).toBe(200);
|
||||
expect(shown.body.text).toContain('Booking reference ABC123');
|
||||
expect((await preview(OTHER)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('MAIL-E2E-004: an upload that is no mail, and a closed body, are refused', async () => {
|
||||
const pdf = await request(server)
|
||||
.post('/api/mail-ingest/upload')
|
||||
.set(as(USER))
|
||||
.attach('file', Buffer.from('%PDF-1.4'), { filename: 'ticket.pdf', contentType: 'application/pdf' });
|
||||
expect(pdf.status).toBe(400);
|
||||
const extra = await request(server).post('/api/mail-ingest/candidates/1/undo').set(as(USER)).send({ token: 'x' });
|
||||
expect(extra.status).toBe(400);
|
||||
});
|
||||
|
||||
it('MAIL-E2E-005: a trip address is made by a member who may add bookings, and hidden from others', async () => {
|
||||
const path = `/api/trips/${tripId}/mail-ingest/address`;
|
||||
const made = await request(server).post(path).set(as(USER));
|
||||
expect(made.status).toBe(200);
|
||||
expect(made.body.address).toMatchObject({ trip_id: tripId });
|
||||
expect((await request(server).get(path).set(as(USER))).body).toEqual(made.body);
|
||||
expect((await request(server).get(path).set(as(OTHER))).status).toBe(404);
|
||||
expect((await request(server).delete(path).set(as(USER))).body).toEqual({ success: true });
|
||||
expect((await request(server).get(path).set(as(USER))).body).toEqual({ address: null });
|
||||
});
|
||||
|
||||
it('MAIL-E2E-006: the status card and the connection test are the admin’s, and hold counts only', async () => {
|
||||
expect((await request(server).get('/api/admin/mail-ingest/status').set(as(USER))).status).toBe(403);
|
||||
const status = await request(server).get('/api/admin/mail-ingest/status').set(as(ADMIN));
|
||||
expect(status.status).toBe(200);
|
||||
expect(status.body).toMatchObject({ transport: 'off', last_day: { by_status: { processed: 1 } } });
|
||||
expect(JSON.stringify(status.body)).not.toContain('LH 716');
|
||||
const test = await request(server).post('/api/admin/mail-ingest/test').set(as(ADMIN));
|
||||
expect(test.status).toBe(200);
|
||||
expect(test.body).toMatchObject({ transport: 'off', ok: false });
|
||||
});
|
||||
|
||||
it('MAIL-E2E-007: the webhook is a 404 until it is the transport, then takes signed mail only', async () => {
|
||||
const own = await request(server).get('/api/mail-ingest/settings').set(as(USER));
|
||||
const address: string = own.body.address.address;
|
||||
const raw = eml('hook-1', address);
|
||||
const post = (headers: Record<string, string>, body: Buffer = raw) =>
|
||||
request(server)
|
||||
.post('/api/mail-ingest/inbound')
|
||||
.set({ 'Content-Type': 'message/rfc822', ...headers })
|
||||
.send(body);
|
||||
const signed = (timestamp = String(Math.floor(Date.now() / 1000))) => ({
|
||||
'X-Trek-Timestamp': timestamp,
|
||||
'X-Trek-Recipient': address,
|
||||
'X-Trek-Signature': `sha256=${signWebhookMail(SECRET, timestamp, address, raw)}`,
|
||||
});
|
||||
|
||||
expect((await post(signed())).status).toBe(404);
|
||||
await setAppSetting(orm, 'mail_ingest_transport', 'webhook');
|
||||
await setAppSetting(orm, 'mail_ingest_webhook_secret', encrypt_api_key(SECRET));
|
||||
|
||||
expect((await post({})).status).toBe(401);
|
||||
expect((await post(signed(String(Math.floor(Date.now() / 1000) - 3600)))).status).toBe(401);
|
||||
const json = await request(server).post('/api/mail-ingest/inbound').set(signed()).send({ raw: 'x' });
|
||||
expect(json.status).toBe(415);
|
||||
|
||||
const taken = await post(signed());
|
||||
expect(taken.status).toBe(200);
|
||||
expect(taken.body).toEqual({ accepted: true, duplicate: false });
|
||||
expect((await post(signed())).body).toEqual({ accepted: true, duplicate: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Native sign-in hand-off e2e: the real CookieAuthGuard, the real cookie
|
||||
* helpers, the real AuthService and session table over a migrated temp SQLite
|
||||
* db. Walks the whole round trip the apps make: the browser side mints a code
|
||||
* for a challenge, the WebView side redeems it with the verifier and walks
|
||||
* away with a session cookie that /api/auth/me accepts.
|
||||
*/
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { AuthModule } from '../../src/nest/auth/auth.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { NativeAuthModule } from '../../src/nest/native-auth/native-auth.module';
|
||||
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { findRows } from '../helpers/factories/rows';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie, signSession } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const verifier = randomBytes(32).toString('base64url');
|
||||
const challenge = createHash('sha256').update(verifier).digest('hex');
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let orm: TestOrm;
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let userId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule, NativeAuthModule],
|
||||
})
|
||||
.overrideProvider(MailerService)
|
||||
.useValue({ sendPasswordResetEmail: vi.fn() })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const handoff = (cookie: string, body: object = { challenge }) =>
|
||||
request(server).post('/api/auth/native/handoff').set('Cookie', cookie).send(body);
|
||||
const exchange = (body: object) => request(server).post('/api/auth/native/exchange').send(body);
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
userId = (await makeUser(orm, { username: 'native-e2e', email: 'native-e2e@example.test' })).user.id;
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetRateLimits(app);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
describe('Native sign-in hand-off e2e', () => {
|
||||
it('NATIVE-E2E-001: carries a browser session into a fresh session cookie for the app', async () => {
|
||||
const minted = await handoff(sessionCookie(userId));
|
||||
expect(minted.status).toBe(200);
|
||||
expect(typeof minted.body.code).toBe('string');
|
||||
|
||||
const redeemed = await exchange({ code: minted.body.code, verifier });
|
||||
expect(redeemed.status).toBe(200);
|
||||
expect(redeemed.body).toEqual({ success: true });
|
||||
const cookie = (redeemed.headers['set-cookie'] as unknown as string[]).find((c) => c.startsWith('trek_session='));
|
||||
expect(cookie).toMatch(/HttpOnly/);
|
||||
expect(cookie).toMatch(/Max-Age=\d+/);
|
||||
|
||||
const me = await request(server).get('/api/auth/me').set('Cookie', String(cookie).split(';')[0]);
|
||||
expect(me.status).toBe(200);
|
||||
expect(me.body.user.id).toBe(userId);
|
||||
|
||||
const logins = await findRows(orm, AuditLog, { user: userId, action: 'user.login' });
|
||||
expect(logins.map((row) => JSON.parse(row.details ?? '{}'))).toContainEqual({ method: 'native_app' });
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-002: refuses to mint a code without a cookie session, even for a valid bearer token', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/auth/native/handoff')
|
||||
.set('Authorization', `Bearer ${signSession(userId)}`)
|
||||
.send({ challenge });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.code).toBe('COOKIE_AUTH_REQUIRED');
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-003: validates the challenge shape', async () => {
|
||||
expect((await handoff(sessionCookie(userId), { challenge: 'not-a-hash' })).status).toBe(400);
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-004: refuses a code presented with the wrong verifier, and the code is gone after', async () => {
|
||||
const { code } = (await handoff(sessionCookie(userId))).body as { code: string };
|
||||
const wrong = await exchange({ code, verifier: 'x'.repeat(43) });
|
||||
expect(wrong.status).toBe(400);
|
||||
expect(wrong.body).toEqual({ error: 'Invalid or expired code' });
|
||||
expect(wrong.headers['set-cookie']).toBeUndefined();
|
||||
|
||||
const retry = await exchange({ code, verifier });
|
||||
expect(retry.status).toBe(400);
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-005: rate-limits the exchange per ip', async () => {
|
||||
// One after another: twenty requests at once reset the ephemeral test server's connections.
|
||||
await Array.from({ length: 20 }).reduce<Promise<unknown>>(
|
||||
(previous, _, i) => previous.then(() => exchange({ code: `nope-${i}`, verifier })),
|
||||
Promise.resolve(),
|
||||
);
|
||||
const blocked = await exchange({ code: 'nope', verifier });
|
||||
expect(blocked.status).toBe(429);
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-006: the browser starts at a page under /api that forwards to the handoff page', async () => {
|
||||
const res = await request(server).get(`/api/auth/native/start?challenge=${challenge}&start=oidc`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toMatch(/text\/html/);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
expect(res.text).toContain(`data-target="/native-handoff?challenge=${challenge}&start=oidc"`);
|
||||
|
||||
expect((await request(server).get('/api/auth/native/start?challenge=nope')).status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -555,6 +555,45 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── KML export (#1866): the places as pins for Google My Maps ─────────────
|
||||
describe('GET export.kml (#1866)', () => {
|
||||
it('serves every place with coordinates as a pin, named after the trip', async () => {
|
||||
await upsertRow(orm, Trips, { id: 5, title: 'Alpine week', user: 1 });
|
||||
await insertRow(orm, Places, { id: 1, trip: 5, name: 'Trailhead', lat: 47.1, lng: 11.2, address: 'Hut road 1' });
|
||||
await insertRow(orm, Places, { id: 2, trip: 5, name: 'Somewhere', lat: null, lng: null });
|
||||
|
||||
const res = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('application/vnd.google-earth.kml+xml');
|
||||
expect(res.headers['content-disposition']).toBe('attachment; filename="Alpine-week.kml"');
|
||||
expect(res.text).toContain('<name>Trailhead</name>');
|
||||
expect(res.text).toContain('<address>Hut road 1</address>');
|
||||
expect(res.text).toContain('<coordinates>11.2,47.1</coordinates>');
|
||||
expect(res.text).not.toContain('Somewhere');
|
||||
});
|
||||
|
||||
it('404s a trip without a place to pin, and one the caller cannot reach', async () => {
|
||||
await upsertRow(orm, Trips, { id: 5, title: 'Nothing here', user: 1 });
|
||||
const empty = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
|
||||
expect(empty.status).toBe(404);
|
||||
expect(empty.body).toEqual({ error: 'Nothing to export' });
|
||||
|
||||
await deleteRows(orm, Trips, { id: 5 });
|
||||
const gone = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
|
||||
expect(gone.status).toBe(404);
|
||||
expect(gone.body).toEqual({ error: 'Trip not found' });
|
||||
expect((await request(server).get('/api/trips/5/places/export.kml')).status).toBe(401);
|
||||
});
|
||||
|
||||
it('is a read: no place_edit permission required', async () => {
|
||||
await upsertRow(orm, Trips, { id: 5, title: 'Alpine week', user: 1 });
|
||||
await insertRow(orm, Places, { id: 1, trip: 5, name: 'Trailhead', lat: 47.1, lng: 11.2 });
|
||||
checkPermission.mockReturnValue(false);
|
||||
const res = await request(server).get('/api/trips/5/places/export.kml').set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
// The reason places keeps its inline checks on the write routes: a guard runs
|
||||
// before the pipe, so guarding create would answer 404 where the suite above
|
||||
// pins a 400. This is the non-regression pin for that decision.
|
||||
|
||||
@@ -184,7 +184,7 @@ describe('Photos through AI Parsing e2e', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.items).toHaveLength(1);
|
||||
expect(res.body.files).toEqual([{ fileName: 'ticket.png', aiAvailable: true, aiUsed: true }]);
|
||||
expect(res.body.files).toEqual([{ fileName: 'ticket.png', aiAvailable: true, aiUsed: true, outcome: 'ok' }]);
|
||||
const image = sentUserContent().find((p: { type: string }) => p.type === 'image_url');
|
||||
expect(image.image_url.url).toMatch(/^data:image\/png;base64,/);
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ import { NotificationsService } from '../../src/nest/notifications/notifications
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { ReservationsModule } from '../../src/nest/reservations/reservations.module';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
import {
|
||||
countRows,
|
||||
deleteRows,
|
||||
@@ -36,7 +37,7 @@ import {
|
||||
insertRow,
|
||||
insertRowIgnoringConflict,
|
||||
} from '../helpers/factories/rows';
|
||||
import { makeTrip, makeDay } from '../helpers/factories/trips';
|
||||
import { makeTrip, makeDay, readTripDays } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
@@ -502,4 +503,60 @@ describe('Reservations + accommodations e2e (real auth guard + temp SQLite, real
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
// Adding notes to two time-only Shinkansen bookings from the browser took them
|
||||
// off their days: the stored "12:00" resolved to no day, and the day_id the PUT
|
||||
// left out was written as null.
|
||||
describe('a partial update keeps the day it does not name', () => {
|
||||
let days: number[];
|
||||
let datedTripId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
datedTripId = (await makeTrip(orm, 1, { title: 'Japan', start_date: '2026-11-10', end_date: '2026-11-12' })).id;
|
||||
days = (await readTripDays(orm, datedTripId)).map((d) => d.id);
|
||||
});
|
||||
|
||||
async function seedTrain(reservationTime: string, dayId: number | null) {
|
||||
const train = await makeReservation(orm, datedTripId, {
|
||||
title: 'Shinkansen',
|
||||
type: 'train',
|
||||
reservation_time: reservationTime,
|
||||
day: dayId,
|
||||
});
|
||||
return train.id;
|
||||
}
|
||||
|
||||
function put(reservationId: number, body: Record<string, unknown>) {
|
||||
return request(server)
|
||||
.put(`/api/trips/${datedTripId}/reservations/${reservationId}`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send(body);
|
||||
}
|
||||
|
||||
it('200 a notes-only update leaves a time-only booking on its day', async () => {
|
||||
const rid = await seedTrain('12:00', days[1]);
|
||||
const res = await put(rid, { notes: 'Car 7, seats 12A-B' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.reservation).toMatchObject({
|
||||
notes: 'Car 7, seats 12A-B',
|
||||
reservation_time: '12:00',
|
||||
day_id: days[1],
|
||||
});
|
||||
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: days[1] });
|
||||
});
|
||||
|
||||
it('200 a dated time still moves the booking to the day it names', async () => {
|
||||
const rid = await seedTrain('12:00', days[0]);
|
||||
const res = await put(rid, { reservation_time: '2026-11-12T09:00' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: days[2] });
|
||||
});
|
||||
|
||||
it('200 an explicit day_id null still takes the booking off its day', async () => {
|
||||
const rid = await seedTrain('12:00', days[1]);
|
||||
const res = await put(rid, { day_id: null, notes: 'Not planned yet' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await findRow(orm, Reservations, { id: rid })).toMatchObject({ day_id: null });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,7 +39,8 @@ const { db } = vi.hoisted(() => {
|
||||
// is_archived, reminder_days, the timestamps and added_at), so those are here too.
|
||||
tmp.exec(`CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT 'Trip', currency TEXT, is_archived INTEGER DEFAULT 0, reminder_days INTEGER DEFAULT 3,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
costs_mode TEXT NOT NULL DEFAULT 'split');`);
|
||||
tmp.exec(`CREATE TABLE trip_members (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL, added_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
|
||||
return { db: tmp };
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* Trip tags e2e for an MCP client: the four trip tag tools and the `tags` the
|
||||
* place tools take, called through a real MCP session on the whole app
|
||||
* (buildApp, the real registry with its scopes and error mapper, the real
|
||||
* services and a migrated temp SQLite), the way an assistant tags a trip.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { makePlace, makeTag, tagPlace } from '../helpers/factories/places';
|
||||
import { addTripMember, makeDay, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
|
||||
interface TagAnswer {
|
||||
id: number;
|
||||
name: string;
|
||||
color: string;
|
||||
trip_id?: number | null;
|
||||
user_id?: number;
|
||||
}
|
||||
interface Answer {
|
||||
tags?: TagAnswer[];
|
||||
tag?: TagAnswer;
|
||||
place?: { id: number; tags: TagAnswer[] };
|
||||
success?: boolean;
|
||||
}
|
||||
|
||||
const NO_ACCESS = 'Trip not found or access denied.';
|
||||
|
||||
/** The tools `userId` is offered with `scopes`, and one call of `tool`: its JSON, or the text of its error. */
|
||||
async function call(userId: number, tool: string, args: Record<string, unknown>, scopes: string[] | null = null) {
|
||||
const server = createLocalMcpServer('TREK trip tags e2e');
|
||||
const around = (_info: unknown, run: () => unknown): unknown => withRequestContext(orm, run);
|
||||
await withRequestContext(orm, () =>
|
||||
app
|
||||
.get(McpRegistryService)
|
||||
.attach(server, { userId, scopes, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
|
||||
);
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'trip-tags-e2e', version: '1.0.0' });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
try {
|
||||
const offered = (await client.listTools()).tools.map((entry) => entry.name);
|
||||
if (!offered.includes(tool)) return { offered, answer: null, error: null };
|
||||
const result = await client.callTool({ name: tool, arguments: args });
|
||||
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
|
||||
const text = content[0]?.text ?? '';
|
||||
if (result.isError === true) return { offered, answer: null, error: text };
|
||||
return { offered, answer: JSON.parse(text) as Answer, error: null };
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
const names = (answer: Answer | null) => (answer?.tags ?? []).map((tag) => tag.name);
|
||||
const tagIds = (answer: Answer | null) => (answer?.place?.tags ?? []).map((tag) => tag.id).sort((a, b) => a - b);
|
||||
|
||||
/** A trip of `owner` with `member` on it; `stranger` is on neither and has a trip of their own. */
|
||||
async function scene() {
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const { user: member } = await makeUser(orm);
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, owner.id, { title: 'Lisbon' });
|
||||
await addTripMember(orm, trip.id, member.id, owner.id);
|
||||
const elsewhere = await makeTrip(orm, stranger.id, { title: 'Porto' });
|
||||
return { owner, member, stranger, trip, elsewhere };
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
describe('the tags of a trip over MCP', () => {
|
||||
it('TRIPTAG-MCP-001: a member adds a tag every member then lists, renames and deletes', async () => {
|
||||
const s = await scene();
|
||||
const tripId = s.trip.id;
|
||||
|
||||
const created = await call(s.member.id, 'create_trip_tag', { tripId, name: ' Monument ', color: '#ff0000' });
|
||||
expect(created.error).toBeNull();
|
||||
expect(created.answer?.tag).toMatchObject({ name: 'Monument', color: '#ff0000', trip_id: tripId });
|
||||
const tagId = created.answer?.tag?.id ?? 0;
|
||||
|
||||
// The same name again, in another case and by somebody else, is that tag.
|
||||
const again = await call(s.owner.id, 'create_trip_tag', { tripId, name: 'MONUMENT' });
|
||||
expect(again.answer?.tag).toMatchObject({ id: tagId, name: 'Monument', color: '#ff0000' });
|
||||
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument']);
|
||||
|
||||
const renamed = await call(s.owner.id, 'update_trip_tag', { tripId, tagId, name: 'Landmark' });
|
||||
expect(renamed.answer?.tag).toMatchObject({ id: tagId, name: 'Landmark', color: '#ff0000' });
|
||||
expect(names((await call(s.member.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Landmark']);
|
||||
|
||||
const deleted = await call(s.member.id, 'delete_trip_tag', { tripId, tagId });
|
||||
expect(deleted.answer).toEqual({ success: true });
|
||||
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual([]);
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-002: lists the trip’s tags only, never a personal one or another trip’s', async () => {
|
||||
const s = await scene();
|
||||
await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' });
|
||||
await makeTag(orm, s.owner.id, { name: 'personal' });
|
||||
await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' });
|
||||
|
||||
expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual(['Zone']);
|
||||
// And the personal list keeps to itself.
|
||||
expect(names((await call(s.owner.id, 'list_tags', {})).answer)).toEqual(['personal']);
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-003: refuses a trip the caller is not on, a tag that is not the trip’s and a taken name', async () => {
|
||||
const s = await scene();
|
||||
const tripId = s.trip.id;
|
||||
const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' });
|
||||
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
|
||||
const personal = await makeTag(orm, s.owner.id, { name: 'personal' });
|
||||
|
||||
expect((await call(s.stranger.id, 'list_trip_tags', { tripId })).error).toBe(NO_ACCESS);
|
||||
expect((await call(s.stranger.id, 'create_trip_tag', { tripId, name: 'Mine' })).error).toBe(NO_ACCESS);
|
||||
expect((await call(s.stranger.id, 'update_trip_tag', { tripId, tagId: zone.id, name: 'Mine' })).error).toBe(
|
||||
NO_ACCESS,
|
||||
);
|
||||
expect((await call(s.stranger.id, 'delete_trip_tag', { tripId, tagId: zone.id })).error).toBe(NO_ACCESS);
|
||||
|
||||
expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: personal.id, name: 'x' })).error).toBe(
|
||||
'Tag not found.',
|
||||
);
|
||||
expect((await call(s.owner.id, 'delete_trip_tag', { tripId, tagId: personal.id })).error).toBe('Tag not found.');
|
||||
expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: monument.id, name: 'zone' })).error).toBe(
|
||||
'A tag with this name already exists',
|
||||
);
|
||||
expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument', 'Zone']);
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-004: a write needs the right to edit the trip’s places', async () => {
|
||||
const s = await scene();
|
||||
const check = vi.spyOn(app.get(PermissionsService), 'checkPermission').mockResolvedValue(false);
|
||||
try {
|
||||
const refused = await call(s.member.id, 'create_trip_tag', { tripId: s.trip.id, name: 'Zone' });
|
||||
expect(refused.error).toBe('You do not have permission to perform this action on this trip.');
|
||||
expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual([]);
|
||||
} finally {
|
||||
check.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-005: reading takes the places read scope and writing the write scope', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const offeredTo = async (scopes: string[]) => (await call(user.id, 'no_such_tool', {}, scopes)).offered;
|
||||
const writes = ['create_trip_tag', 'delete_trip_tag', 'update_trip_tag'];
|
||||
const writesOf = (offered: string[]) => offered.filter((tool) => writes.includes(tool)).sort();
|
||||
|
||||
const reader = await offeredTo(['places:read']);
|
||||
expect(reader).toContain('list_trip_tags');
|
||||
expect(writesOf(reader)).toEqual([]);
|
||||
expect(writesOf(await offeredTo(['places:write']))).toEqual(writes);
|
||||
expect(await offeredTo(['trips:read'])).not.toContain('list_trip_tags');
|
||||
});
|
||||
});
|
||||
|
||||
describe('tags on the MCP place tools', () => {
|
||||
it('TRIPTAG-MCP-010: a new place takes the trip’s tags and the personal tags of people on it, nothing else', async () => {
|
||||
const s = await scene();
|
||||
const tripId = s.trip.id;
|
||||
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
|
||||
const ownPersonal = await makeTag(orm, s.member.id, { name: 'mine' });
|
||||
const foreignTrip = await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' });
|
||||
const foreignPersonal = await makeTag(orm, s.stranger.id, { name: 'theirs' });
|
||||
|
||||
const created = await call(s.member.id, 'create_place', {
|
||||
tripId,
|
||||
name: 'Belem Tower',
|
||||
tags: [monument.id, ownPersonal.id, foreignTrip.id, foreignPersonal.id],
|
||||
});
|
||||
|
||||
expect(created.error).toBeNull();
|
||||
expect(tagIds(created.answer)).toEqual([monument.id, ownPersonal.id].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-011: create_and_assign_place tags the place it plans', async () => {
|
||||
const s = await scene();
|
||||
const day = await makeDay(orm, s.trip.id, { day_number: 1 });
|
||||
const zone = await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' });
|
||||
|
||||
const created = await call(s.owner.id, 'create_and_assign_place', {
|
||||
tripId: s.trip.id,
|
||||
dayId: day.id,
|
||||
name: 'Alfama',
|
||||
tags: [zone.id],
|
||||
});
|
||||
|
||||
expect(created.error).toBeNull();
|
||||
expect(tagIds(created.answer)).toEqual([zone.id]);
|
||||
});
|
||||
|
||||
it('TRIPTAG-MCP-012: an update replaces the tags it names, keeps them when it names none and clears them on []', async () => {
|
||||
const s = await scene();
|
||||
const tripId = s.trip.id;
|
||||
const place = await makePlace(orm, tripId, { name: 'Belem Tower' });
|
||||
const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' });
|
||||
const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' });
|
||||
await tagPlace(orm, place.id, [monument.id]);
|
||||
const update = (args: Record<string, unknown>) =>
|
||||
call(s.member.id, 'update_place', { tripId, placeId: place.id, ...args });
|
||||
|
||||
expect(tagIds((await update({ notes: 'By the river' })).answer)).toEqual([monument.id]);
|
||||
expect(tagIds((await update({ tags: [zone.id] })).answer)).toEqual([zone.id]);
|
||||
expect(tagIds((await update({ tags: [] })).answer)).toEqual([]);
|
||||
expect((await update({ tags: ['zone'] })).error).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Trip tags e2e: the /api/trips/:tripId/tags routes through the real
|
||||
* JwtAuthGuard and TripAccessGuard against a migrated temp SQLite db
|
||||
* (createSnapshotTestDb()). TripTagsService and the trip access check run
|
||||
* their real queries; rows are seeded and read through the factories in
|
||||
* tests/helpers/factories. The permission check is a spy, so a case can take
|
||||
* the `place_edit` right away, and the broadcasts go to a FakeRealtimeService.
|
||||
*/
|
||||
import { Tags } from '../../src/db/entities/Tags.entity';
|
||||
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { TagsModule } from '../../src/nest/tags/tags.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeTag } from '../helpers/factories/places';
|
||||
import { countRows, deleteRows, findRow } from '../helpers/factories/rows';
|
||||
import { addTripMember, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const realtime = new FakeRealtimeService();
|
||||
const broadcast = realtime.broadcastMock;
|
||||
|
||||
// A spy on the container's PermissionsService, created in beforeAll once the app is built.
|
||||
let checkPermission: MockInstance;
|
||||
|
||||
let orm: TestOrm;
|
||||
|
||||
const OWNER = 1;
|
||||
const MEMBER = 2;
|
||||
const STRANGER = 3;
|
||||
|
||||
describe('Trip tags e2e (real auth and trip guards + real SQL over temp SQLite)', () => {
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let tripId: number;
|
||||
let otherTripId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, TagsModule],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(realtime)
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
// Mirror the production APP_PIPE (app.module.ts): the DTO-typed bodies
|
||||
// validate by metatype, exactly as they do under buildApp().
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const tagsPath = (trip = tripId) => `/api/trips/${trip}/tags`;
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
// Pinned ids: sessionCookie(n) signs for exactly these users.
|
||||
await makeUser(orm, { id: OWNER, username: 'e2e-owner', email: 'owner@example.test' });
|
||||
await makeUser(orm, { id: MEMBER, username: 'e2e-member', email: 'member@example.test' });
|
||||
await makeUser(orm, { id: STRANGER, username: 'e2e-stranger', email: 'stranger@example.test' });
|
||||
app = await build();
|
||||
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await deleteRows(orm, Tags);
|
||||
await deleteRows(orm, TripMembers);
|
||||
await deleteRows(orm, Trips);
|
||||
tripId = (await makeTrip(orm, OWNER, { title: 'Lisbon' })).id;
|
||||
await addTripMember(orm, tripId, MEMBER, OWNER);
|
||||
otherTripId = (await makeTrip(orm, STRANGER, { title: 'Porto' })).id;
|
||||
checkPermission.mockResolvedValue(true);
|
||||
broadcast.mockClear();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('401 without a session cookie', async () => {
|
||||
const res = await request(server).get(tagsPath());
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('200 list: the same tags for every member, by name, without personal ones', async () => {
|
||||
await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
|
||||
await makeTag(orm, MEMBER, { trip: tripId, name: 'Activity' });
|
||||
await makeTag(orm, OWNER, { name: 'personal' });
|
||||
await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' });
|
||||
|
||||
const asOwner = await request(server).get(tagsPath()).set('Cookie', sessionCookie(OWNER));
|
||||
const asMember = await request(server).get(tagsPath()).set('Cookie', sessionCookie(MEMBER));
|
||||
|
||||
expect(asOwner.status).toBe(200);
|
||||
expect(asOwner.body.tags.map((tag: { name: string }) => tag.name)).toEqual(['Activity', 'Zone']);
|
||||
expect(asMember.body).toEqual(asOwner.body);
|
||||
});
|
||||
|
||||
it('404 on every route for a trip the user is not on', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
|
||||
const cookie = sessionCookie(STRANGER);
|
||||
|
||||
const list = await request(server).get(tagsPath()).set('Cookie', cookie);
|
||||
const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' });
|
||||
const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
|
||||
const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie);
|
||||
|
||||
for (const res of [list, create, update, remove]) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Trip not found' });
|
||||
}
|
||||
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Zone' });
|
||||
});
|
||||
|
||||
it('201 on create by a member: the tag is the trip’s, with the default colour, and the trip is told', async () => {
|
||||
const res = await request(server)
|
||||
.post(tagsPath())
|
||||
.set('Cookie', sessionCookie(MEMBER))
|
||||
.set('X-Socket-Id', 'sock-9')
|
||||
.send({ name: ' Monument ' });
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tag).toMatchObject({ name: 'Monument', color: '#10b981', trip_id: tripId, user_id: MEMBER });
|
||||
expect(await findRow(orm, Tags, { id: res.body.tag.id })).toMatchObject({ name: 'Monument', trip_id: tripId });
|
||||
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]);
|
||||
});
|
||||
|
||||
it('201 on create with a name the trip has: answers that tag and makes no second one', async () => {
|
||||
const existing = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' });
|
||||
|
||||
const res = await request(server)
|
||||
.post(tagsPath())
|
||||
.set('Cookie', sessionCookie(MEMBER))
|
||||
.send({ name: 'MONUMENT', color: '#00ff00' });
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tag).toMatchObject({ id: existing.id, name: 'Monument', color: '#ff0000' });
|
||||
expect(await countRows(orm, Tags, { trip: tripId })).toBe(1);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('400 from the Zod pipe on create without a name, and with a colour that is not hex', async () => {
|
||||
const cookie = sessionCookie(OWNER);
|
||||
const unnamed = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: ' ' });
|
||||
const coloured = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Zone', color: 'red' });
|
||||
|
||||
expect(unnamed.status).toBe(400);
|
||||
expect(unnamed.body.error).toContain('name');
|
||||
expect(coloured.status).toBe(400);
|
||||
expect(coloured.body.error).toContain('color');
|
||||
expect(await countRows(orm, Tags, { trip: tripId })).toBe(0);
|
||||
});
|
||||
|
||||
it('403 on every write without the right to edit the trip’s places; reading stays open', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
|
||||
checkPermission.mockResolvedValue(false);
|
||||
const cookie = sessionCookie(MEMBER);
|
||||
|
||||
const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' });
|
||||
const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
|
||||
const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie);
|
||||
const list = await request(server).get(tagsPath()).set('Cookie', cookie);
|
||||
|
||||
for (const res of [create, update, remove]) {
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).toEqual({ error: 'No permission' });
|
||||
}
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body.tags.map((row: { name: string }) => row.name)).toEqual(['Zone']);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('200 on update: a member renames and recolours a tag the owner created', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' });
|
||||
|
||||
const res = await request(server)
|
||||
.put(`${tagsPath()}/${tag.id}`)
|
||||
.set('Cookie', sessionCookie(MEMBER))
|
||||
.send({ name: 'Landmark', color: '#0ea5e9' });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tag).toMatchObject({ id: tag.id, name: 'Landmark', color: '#0ea5e9', user_id: OWNER });
|
||||
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, undefined]]);
|
||||
});
|
||||
|
||||
it('409 on update onto the name of another tag of the trip', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
|
||||
await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' });
|
||||
|
||||
const res = await request(server)
|
||||
.put(`${tagsPath()}/${tag.id}`)
|
||||
.set('Cookie', sessionCookie(OWNER))
|
||||
.send({ name: 'zone' });
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body).toEqual({ error: 'A tag with this name already exists' });
|
||||
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' });
|
||||
});
|
||||
|
||||
it('404 on update and delete of a personal tag and of another trip’s tag', async () => {
|
||||
const personal = await makeTag(orm, OWNER, { name: 'personal' });
|
||||
const foreign = await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' });
|
||||
const cookie = sessionCookie(OWNER);
|
||||
|
||||
const renamePersonal = await request(server)
|
||||
.put(`${tagsPath()}/${personal.id}`)
|
||||
.set('Cookie', cookie)
|
||||
.send({ name: 'Mine' });
|
||||
const deletePersonal = await request(server).delete(`${tagsPath()}/${personal.id}`).set('Cookie', cookie);
|
||||
const renameForeign = await request(server)
|
||||
.put(`${tagsPath()}/${foreign.id}`)
|
||||
.set('Cookie', cookie)
|
||||
.send({ name: 'Mine' });
|
||||
const deleteForeign = await request(server).delete(`${tagsPath()}/${foreign.id}`).set('Cookie', cookie);
|
||||
|
||||
for (const res of [renamePersonal, deletePersonal, renameForeign, deleteForeign]) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Tag not found' });
|
||||
}
|
||||
expect(await countRows(orm, Tags, {})).toBe(2);
|
||||
});
|
||||
|
||||
it('200 on delete: the row goes and the trip is told', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
|
||||
|
||||
const res = await request(server)
|
||||
.delete(`${tagsPath()}/${tag.id}`)
|
||||
.set('Cookie', sessionCookie(MEMBER))
|
||||
.set('X-Socket-Id', 'sock-9');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true });
|
||||
expect(await findRow(orm, Tags, { id: tag.id })).toBeNull();
|
||||
expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]);
|
||||
});
|
||||
|
||||
it('a tag of a trip stays off its creator’s personal /api/tags, which cannot change it either', async () => {
|
||||
const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' });
|
||||
const cookie = sessionCookie(OWNER);
|
||||
|
||||
const list = await request(server).get('/api/tags').set('Cookie', cookie);
|
||||
const update = await request(server).put(`/api/tags/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' });
|
||||
const remove = await request(server).delete(`/api/tags/${tag.id}`).set('Cookie', cookie);
|
||||
|
||||
expect(list.body).toEqual({ tags: [] });
|
||||
expect(update.status).toBe(404);
|
||||
expect(remove.status).toBe(404);
|
||||
expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' });
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,7 @@ import { VacayPlans } from '../../src/db/entities/VacayPlans.entity';
|
||||
import { GUEST_HAS_PAYMENTS } from '../../src/nest/budget/budget-departure.helpers';
|
||||
import { BudgetService } from '../../src/nest/budget/budget.service';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
@@ -108,6 +109,8 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
// The contracts are checked at the pipe, as in the app (APP_PIPE).
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
@@ -243,6 +246,26 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(await dayIds(week.body.trip.id)).toEqual(kept);
|
||||
});
|
||||
|
||||
it('200 update keeps the costs as totals only, the trip as it was otherwise; 400 on another mode (#1714)', async () => {
|
||||
const trip = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'Lisbon' });
|
||||
expect(trip.body.trip.costs_mode).toBe('split');
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/${trip.body.trip.id}`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ costs_mode: 'totals' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.trip).toMatchObject({ title: 'Lisbon', costs_mode: 'totals' });
|
||||
const audit = await findRow(orm, AuditLog, { action: 'trip.update' });
|
||||
expect(JSON.parse(audit?.details ?? '{}')).toMatchObject({ costs_mode: 'totals' });
|
||||
|
||||
const bogus = await request(server)
|
||||
.put(`/api/trips/${trip.body.trip.id}`)
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ costs_mode: 'shares' });
|
||||
expect(bogus.status).toBe(400);
|
||||
expect((await findRow(orm, Trips, { id: trip.body.trip.id }))?.costs_mode).toBe('totals');
|
||||
});
|
||||
|
||||
it('200 update with a later start moves the leave days of the owner along, off the blocked weekend, and tells the plan (#2604)', async () => {
|
||||
// 2030-11-25 is a Monday; the plan blocks Saturday and Sunday by default.
|
||||
const trip = await request(server)
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* GET /api/trips/:tripId/reservations/:id/wallet-pass end to end: the session,
|
||||
* the trip guard, the booking read through the reservations module and the
|
||||
* request the TREK services' pass signer receives. The signer itself is
|
||||
* stubbed at the fetch seam.
|
||||
*/
|
||||
import { servicesConfig } from '../../src/nest/app-config/tokens';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { WalletPassModule } from '../../src/nest/wallet-pass/wallet-pass.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() }));
|
||||
vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../src/utils/ssrfGuard')>()),
|
||||
safeFetchAdminConfigured,
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const OWNER = 1;
|
||||
const STRANGER = 2;
|
||||
const PASS = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from('signed pass')]);
|
||||
|
||||
let orm: TestOrm;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let tripId: number;
|
||||
let flightId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), WalletPassModule],
|
||||
})
|
||||
.overrideProvider(servicesConfig.KEY)
|
||||
.useValue({ mode: 'auto', key: null, hosts: [], walletPassUrl: 'https://push.liketrek.com/v1/wallet/pass' })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const path = (trip: number, id: number, lang = 'de') =>
|
||||
`/api/trips/${trip}/reservations/${id}/wallet-pass?lang=${lang}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: OWNER, username: 'owner', email: 'owner@example.test' });
|
||||
await makeUser(orm, { id: STRANGER, username: 'stranger', email: 'stranger@example.test' });
|
||||
const trip = await makeTrip(orm, OWNER, { title: 'Japan 2027' });
|
||||
tripId = trip.id;
|
||||
const flight = await makeReservation(orm, tripId, {
|
||||
title: 'LH 716',
|
||||
type: 'flight',
|
||||
reservation_time: '2027-04-01T13:25',
|
||||
confirmation_number: 'X7K2QP',
|
||||
metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', seat: '34K' }),
|
||||
});
|
||||
flightId = flight.id;
|
||||
await makeReservationEndpoint(orm, flightId, {
|
||||
role: 'from',
|
||||
name: 'Frankfurt',
|
||||
code: 'FRA',
|
||||
lat: 50.03,
|
||||
lng: 8.57,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2027-04-01',
|
||||
local_time: '13:25',
|
||||
});
|
||||
await makeReservationEndpoint(orm, flightId, {
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Tokyo Haneda',
|
||||
code: 'HND',
|
||||
lat: 35.55,
|
||||
lng: 139.78,
|
||||
timezone: 'Asia/Tokyo',
|
||||
local_date: '2027-04-02',
|
||||
local_time: '08:50',
|
||||
});
|
||||
app = await build();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
safeFetchAdminConfigured.mockReset();
|
||||
safeFetchAdminConfigured.mockResolvedValue(
|
||||
new Response(PASS, { status: 200, headers: { 'content-type': 'application/vnd.apple.pkpass' } }),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
describe('GET /api/trips/:tripId/reservations/:id/wallet-pass', () => {
|
||||
it('WALLET-E2E-001: answers 401 without a session and asks nobody', async () => {
|
||||
const res = await request(app.getHttpServer()).get(path(tripId, flightId));
|
||||
expect(res.status).toBe(401);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-002: someone outside the trip gets a 404, not a pass', async () => {
|
||||
const res = await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(STRANGER));
|
||||
expect(res.status).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-003: the owner gets the signed pass, built from the booking in their language', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(path(tripId, flightId))
|
||||
.set(as(OWNER))
|
||||
.buffer(true)
|
||||
.parse((r, done) => {
|
||||
const chunks: Buffer[] = [];
|
||||
r.on('data', (c: Buffer) => chunks.push(c));
|
||||
r.on('end', () => done(null, Buffer.concat(chunks)));
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('application/vnd.apple.pkpass');
|
||||
expect(res.headers['content-disposition']).toBe('attachment; filename="LH-716.pkpass"');
|
||||
expect(Buffer.compare(res.body as Buffer, PASS)).toBe(0);
|
||||
|
||||
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('https://push.liketrek.com/v1/wallet/pass');
|
||||
const body = JSON.parse(String(init.body));
|
||||
expect(body).toMatchObject({
|
||||
kind: 'flight',
|
||||
title: 'LH 716',
|
||||
trip: 'Japan 2027',
|
||||
start: '2027-04-01T13:25:00+02:00',
|
||||
end: '2027-04-02T08:50:00+09:00',
|
||||
from: { code: 'FRA', name: 'Frankfurt' },
|
||||
to: { code: 'HND', name: 'Tokyo Haneda' },
|
||||
confirmation: { value: 'X7K2QP' },
|
||||
locale: 'de-DE',
|
||||
});
|
||||
expect(body.details.map((d: { label: string }) => d.label)).toContain('Sitzplatz');
|
||||
});
|
||||
|
||||
it('WALLET-E2E-004: a booking of another trip, or none, is a 404', async () => {
|
||||
const other = await makeTrip(orm, OWNER, { title: 'Elsewhere' });
|
||||
expect((await request(app.getHttpServer()).get(path(other.id, flightId)).set(as(OWNER))).status).toBe(404);
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, 999_999)).set(as(OWNER))).status).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-005: a booking without a date gets a 422, and the signer failing a 502', async () => {
|
||||
const undated = await makeReservation(orm, tripId, { title: 'Someday', type: 'event', reservation_time: null });
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, undated.id)).set(as(OWNER))).status).toBe(422);
|
||||
|
||||
safeFetchAdminConfigured.mockRejectedValueOnce(new Error('ECONNREFUSED'));
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(OWNER))).status).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Google Wallet', () => {
|
||||
const google = (trip: number, id: number) => `/api/trips/${trip}/reservations/${id}/wallet-pass/google?lang=de`;
|
||||
const SAVE_URL = 'https://pay.google.com/gp/v/save/eyJhbGciOiJSUzI1NiJ9.payload.signature';
|
||||
const answer = (status: number, body: string, type = 'application/json') =>
|
||||
safeFetchAdminConfigured.mockResolvedValueOnce(new Response(body, { status, headers: { 'content-type': type } }));
|
||||
|
||||
it('WALLET-E2E-006: the owner gets the save link, signed at the Google route beside the Apple one', async () => {
|
||||
answer(200, JSON.stringify({ saveUrl: SAVE_URL }));
|
||||
const res = await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ saveUrl: SAVE_URL });
|
||||
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('https://push.liketrek.com/v1/wallet/google');
|
||||
expect(JSON.parse(String(init.body))).toMatchObject({ kind: 'flight', title: 'LH 716', locale: 'de-DE' });
|
||||
});
|
||||
|
||||
it('WALLET-E2E-007: a stranger, another trip and a missing booking get a 404 and ask nobody', async () => {
|
||||
expect((await request(app.getHttpServer()).get(google(tripId, flightId))).status).toBe(401);
|
||||
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(STRANGER))).status).toBe(404);
|
||||
const other = await makeTrip(orm, OWNER, { title: 'Elsewhere too' });
|
||||
expect((await request(app.getHttpServer()).get(google(other.id, flightId)).set(as(OWNER))).status).toBe(404);
|
||||
expect((await request(app.getHttpServer()).get(google(tripId, 999_999)).set(as(OWNER))).status).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-008: no issuer yet is a 404, a link that is not Google Wallet a 502', async () => {
|
||||
answer(404, 'not found', 'text/plain');
|
||||
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER))).status).toBe(404);
|
||||
answer(200, JSON.stringify({ saveUrl: 'https://evil.example/save' }));
|
||||
expect((await request(app.getHttpServer()).get(google(tripId, flightId)).set(as(OWNER))).status).toBe(502);
|
||||
});
|
||||
|
||||
it('WALLET-E2E-009: the trip members can ask whether Google Wallet works here', async () => {
|
||||
safeFetchAdminConfigured.mockResolvedValueOnce(new Response('', { status: 405 }));
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`/api/trips/${tripId}/reservations/google-wallet`)
|
||||
.set(as(OWNER));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ available: true });
|
||||
expect(
|
||||
(await request(app.getHttpServer()).get(`/api/trips/${tripId}/reservations/google-wallet`).set(as(STRANGER)))
|
||||
.status,
|
||||
).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -93,6 +93,7 @@ export async function accommodationsOver(
|
||||
await createTestJourneyPhotosRepo(conn),
|
||||
await createTestJourneyEntryPhotosRepo(conn),
|
||||
await createTestPlacesRepo(conn),
|
||||
{ releaseValues: async () => 0 } as never, // StorageReleaseService
|
||||
),
|
||||
await createTestUnitOfWork(conn),
|
||||
await createTestDayAssignmentsRepo(conn),
|
||||
|
||||
@@ -33,10 +33,10 @@ export async function setAddonEnabled(orm: FactoryOrm, addonId: string, enabled:
|
||||
await upsertRow(orm, Addons, { id: addonId, name: addonId, type: 'global', enabled }, ['enabled']);
|
||||
}
|
||||
|
||||
/** Collab's chat, notes, polls and next-up panels are opt-out app settings, not addon rows. */
|
||||
/** Collab's chat, notes, polls, links and next-up panels are opt-out app settings, not addon rows. */
|
||||
export async function setCollabFeature(
|
||||
orm: FactoryOrm,
|
||||
feature: 'chat' | 'notes' | 'polls' | 'whatsnext',
|
||||
feature: 'chat' | 'notes' | 'polls' | 'links' | 'whatsnext',
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
await setAppSetting(orm, `collab_${feature}_enabled`, enabled ? 'true' : 'false');
|
||||
|
||||
@@ -361,6 +361,7 @@ export async function createPluginRpcHostParts(
|
||||
await createTestJourneyPhotosRepo(db),
|
||||
await createTestJourneyEntryPhotosRepo(db),
|
||||
await createTestPlacesRepo(db),
|
||||
{ releaseValues: async () => 0 } as never, // StorageReleaseService
|
||||
);
|
||||
const atlas = new AtlasService(
|
||||
await createTestBucketListRepo(db),
|
||||
|
||||
@@ -182,7 +182,7 @@ export function setAddonEnabled(db: Database.Database, addonId: string, enabled:
|
||||
/** Collab's sub-feature flags are opt-out app_settings, not addon rows. */
|
||||
export function setCollabFeature(
|
||||
db: Database.Database,
|
||||
feature: 'chat' | 'notes' | 'polls' | 'whatsnext',
|
||||
feature: 'chat' | 'notes' | 'polls' | 'links' | 'whatsnext',
|
||||
enabled: boolean,
|
||||
): void {
|
||||
db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(
|
||||
|
||||
@@ -89,6 +89,42 @@ describe('Create assignment', () => {
|
||||
await request(app).put(url).send({ end_day: true }).expect(401);
|
||||
});
|
||||
|
||||
it('ASSIGN-STAY: two visits of one place keep their own stay, the other falls back to the place (#3092)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { trip, day, place } = setupAssignmentFixtures(user.id);
|
||||
await updateRows(orm, Places, { id: place.id }, { duration_minutes: 60 });
|
||||
const cookie = authCookie(user.id);
|
||||
const plan = `/api/trips/${trip.id}/days/${day.id}/assignments`;
|
||||
const first = (await request(app).post(plan).set('Cookie', cookie).send({ place_id: place.id }).expect(201)).body
|
||||
.assignment;
|
||||
const second = (await request(app).post(plan).set('Cookie', cookie).send({ place_id: place.id }).expect(201)).body
|
||||
.assignment;
|
||||
expect(first.stay_minutes).toBeNull();
|
||||
|
||||
const url = `/api/trips/${trip.id}/assignments/${second.id}/stay`;
|
||||
const changed = await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: 0 }).expect(200);
|
||||
expect(changed.body.assignment).toMatchObject({ id: second.id, stay_minutes: 0 });
|
||||
|
||||
// The other visit and the place itself are untouched.
|
||||
const listed = await request(app).get(`/api/trips/${trip.id}/days`).set('Cookie', cookie).expect(200);
|
||||
const visits = listed.body.days[0].assignments as Array<{ id: number; stay_minutes: number | null }>;
|
||||
expect(visits.find((a) => a.id === first.id)?.stay_minutes).toBeNull();
|
||||
expect(visits.find((a) => a.id === second.id)?.stay_minutes).toBe(0);
|
||||
expect((await findRows(orm, Places, { id: place.id }))[0]?.duration_minutes).toBe(60);
|
||||
|
||||
await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: -5 }).expect(400);
|
||||
await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: 1.5 }).expect(400);
|
||||
const foreign = createTrip(testDb, user.id);
|
||||
await request(app)
|
||||
.put(`/api/trips/${foreign.id}/assignments/${second.id}/stay`)
|
||||
.set('Cookie', cookie)
|
||||
.send({ stay_minutes: 10 })
|
||||
.expect(404);
|
||||
const reset = await request(app).put(url).set('Cookie', cookie).send({ stay_minutes: null }).expect(200);
|
||||
expect(reset.body.assignment.stay_minutes).toBeNull();
|
||||
await request(app).put(url).send({ stay_minutes: 10 }).expect(401);
|
||||
});
|
||||
|
||||
it('ASSIGN-001 — POST creates assignment linking place to day', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { trip, day, place } = setupAssignmentFixtures(user.id);
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { MailIngestAddresses } from '../../../src/db/entities/MailIngestAddresses.entity';
|
||||
import { MailIngestCandidates } from '../../../src/db/entities/MailIngestCandidates.entity';
|
||||
import { MailIngestMessages } from '../../../src/db/entities/MailIngestMessages.entity';
|
||||
import { Reservations } from '../../../src/db/entities/Reservations.entity';
|
||||
import { dbNow } from '../../../src/db/types';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import {
|
||||
AirtrailClient,
|
||||
type AirtrailAirport,
|
||||
type AirtrailFlightRaw,
|
||||
} from '../../../src/nest/integrations/airtrail.client';
|
||||
import { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
|
||||
import { MailIngestApplyService } from '../../../src/nest/mail-ingest/mail-ingest-apply.service';
|
||||
import { MailIngestTripsService } from '../../../src/nest/mail-ingest/mail-ingest-trips.service';
|
||||
import { UNDO_WINDOW_DAYS } from '../../../src/nest/mail-ingest/mail-ingest.constants';
|
||||
import { sealMail } from '../../../src/nest/mail-ingest/mail-seal';
|
||||
import { makeBudgetItem } from '../../helpers/factories/budget';
|
||||
import { inContext } from '../../helpers/factories/context';
|
||||
import { updateRows } from '../../helpers/factories/rows';
|
||||
import type { CaseGroup } from './types';
|
||||
import { setAppSetting } from '../../helpers/factories/settings';
|
||||
import { makeTrip } from '../../helpers/factories/trips';
|
||||
import type { CaseGroup, Scene } from './types';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
|
||||
import { vi } from 'vitest';
|
||||
|
||||
@@ -130,6 +143,131 @@ function retype(app: INestApplication, id: number, type: string): Promise<number
|
||||
}
|
||||
|
||||
/** Bookings: reservations, transports, transit, stays and the AirTrail import. */
|
||||
// -- The booking mail import --------------------------------------------------
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const orm = (app: INestApplication) => app.get(MikroORM);
|
||||
/** A date `days` from today: the import's checks take a booking only within a few years of now. */
|
||||
const dayFromToday = (days: number) => new Date(Date.now() + days * DAY_MS).toISOString().slice(0, 10);
|
||||
const MAIL_DAY = dayFromToday(30);
|
||||
|
||||
/** A table booking, as a mail to the scene's owner would have been read. */
|
||||
const mailBooking = (s: Scene): BookingImportPreviewItem => ({
|
||||
type: 'restaurant',
|
||||
title: `Dinner ${s.n}`,
|
||||
reservation_time: `${MAIL_DAY}T19:00`,
|
||||
confirmation_number: `MAIL-${s.n}`,
|
||||
source: { fileName: 'mail', index: 0 },
|
||||
});
|
||||
|
||||
/** The scene's inbox entry and, for a move, the trip it goes to, by the scene's number. */
|
||||
const mailEntryOf = new Map<number, number>();
|
||||
const moveTargetOf = new Map<number, number>();
|
||||
const sceneRow = (ids: Map<number, number>, s: Scene) => {
|
||||
const id = ids.get(s.n);
|
||||
if (id === undefined) throw new Error(`scene ${s.n} has no row from its setup`);
|
||||
return id;
|
||||
};
|
||||
const mailEntry = (s: Scene) => sceneRow(mailEntryOf, s);
|
||||
const moveTarget = (s: Scene) => sceneRow(moveTargetOf, s);
|
||||
const mailPath = (s: Scene, action: string) => `/api/mail-ingest/candidates/${mailEntry(s)}/${action}`;
|
||||
|
||||
/** A mail the scene's owner forwarded, as the intake stores it: sealed, and named by its own address. */
|
||||
function forwardedMail(s: Scene): Buffer {
|
||||
return Buffer.from(
|
||||
[
|
||||
'From: Owner <owner@example.com>',
|
||||
'To: trips@example.com',
|
||||
'Subject: Your table',
|
||||
`Message-ID: <parity-${s.n}@example.com>`,
|
||||
'Content-Type: text/plain; charset=utf-8',
|
||||
'',
|
||||
`Table for two, reference MAIL-${s.n}.`,
|
||||
].join('\r\n'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The import switched on, the owner's forwarded mail stored, and one entry
|
||||
* for its booking: waiting in the inbox, or already added to the scene's
|
||||
* trip. The add goes through the import's own write, which sends nothing;
|
||||
* announcing it is the business of the action that adds.
|
||||
*/
|
||||
async function mailEntryFor(s: Scene, app: INestApplication, added: boolean): Promise<void> {
|
||||
const db = orm(app);
|
||||
await setAppSetting(db, 'mail_ingest_enabled', 'true');
|
||||
const now = new Date();
|
||||
const raw = forwardedMail(s);
|
||||
const item = mailBooking(s);
|
||||
const id = await inContext(db, async (em) => {
|
||||
const addressId = await em.getRepository(MailIngestAddresses).insertAddress({
|
||||
userId: s.owner.id,
|
||||
tripId: null,
|
||||
tokenHash: `parity-${s.n}`,
|
||||
tokenEnc: 'sealed',
|
||||
createdAt: dbNow(now),
|
||||
});
|
||||
const messageId = await em.getRepository(MailIngestMessages).insertIfNew({
|
||||
transport: 'upload',
|
||||
messageIdHdr: `<parity-${s.n}@example.com>`,
|
||||
dedupeHash: `parity-${s.n}`,
|
||||
addressId,
|
||||
userId: s.owner.id,
|
||||
tripId: null,
|
||||
size: raw.length,
|
||||
rawEnc: sealMail(raw),
|
||||
receivedAt: dbNow(now),
|
||||
});
|
||||
if (messageId === null) throw new Error(`the mail of scene ${s.n} was stored already`);
|
||||
const entry = {
|
||||
messageId,
|
||||
userId: s.owner.id,
|
||||
position: 0,
|
||||
itemJson: JSON.stringify(item),
|
||||
source: 'kitinerary',
|
||||
checksJson: null,
|
||||
uncertainFields: null,
|
||||
matchJson: null,
|
||||
suggestedTripId: s.trip.id,
|
||||
dedupeKey: null,
|
||||
contentHash: null,
|
||||
createdAt: dbNow(now),
|
||||
};
|
||||
if (!added) {
|
||||
return em
|
||||
.getRepository(MailIngestCandidates)
|
||||
.insertCandidate({ ...entry, resolution: 'pending', reason: 'ask_first' });
|
||||
}
|
||||
const trips = app.get(MailIngestTripsService);
|
||||
const person = await trips.person(s.owner.id);
|
||||
const trip = person ? await trips.editableTrip(person, s.trip.id) : null;
|
||||
if (!trip) throw new Error(`the owner of scene ${s.n} cannot add bookings to its trip`);
|
||||
const apply = app.get(MailIngestApplyService);
|
||||
// test-sql-allow: MailIngestApplyService.prepare builds the booking to write, it is no SQL statement.
|
||||
const prepared = await apply.prepare(item, trip, s.owner.id, []);
|
||||
const written = await app.get(UnitOfWork).transactional(() => apply.writeInTx(prepared));
|
||||
return em.getRepository(MailIngestCandidates).insertCandidate({
|
||||
...entry,
|
||||
resolution: 'applied',
|
||||
reason: null,
|
||||
resolvedTripId: s.trip.id,
|
||||
createdIdsJson: JSON.stringify(written.created),
|
||||
resolvedAt: dbNow(now),
|
||||
undoUntil: dbNow(new Date(now.getTime() + UNDO_WINDOW_DAYS * DAY_MS)),
|
||||
});
|
||||
});
|
||||
mailEntryOf.set(s.n, id);
|
||||
}
|
||||
|
||||
const waitingMail = (s: Scene, app: INestApplication) => mailEntryFor(s, app, false);
|
||||
const addedMail = (s: Scene, app: INestApplication) => mailEntryFor(s, app, true);
|
||||
|
||||
/**
|
||||
* The person's inbox count, sent to every one of their sockets (the asking
|
||||
* tab included, on REST too): each action on an entry changes what waits.
|
||||
*/
|
||||
const INBOX_CHANGED = { event: 'mailInbox:changed', user: 'actor', all: true } as const;
|
||||
|
||||
export const bookings: CaseGroup = {
|
||||
name: 'bookings',
|
||||
prefix: 'BCP-BOOK',
|
||||
@@ -358,6 +496,71 @@ export const bookings: CaseGroup = {
|
||||
settle: true,
|
||||
expect: ['reservation:created', BOOKING_NOTICE],
|
||||
},
|
||||
|
||||
// -- The booking mail import ----------------------------------------------
|
||||
// A booking from a mail is announced once its write committed, to every
|
||||
// socket of the trip, the asking tab included: the same announcement the
|
||||
// import makes when it adds a booking with no tab asking at all.
|
||||
{
|
||||
// The booking, the mail as its document, and the inbox that shrank.
|
||||
tool: 'add_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'apply'), body: () => ({}) },
|
||||
expect: [{ event: 'reservation:created', all: true }, { event: 'file:created', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
// Out of the scene's trip into the owner's other trip in the booking's dates, its mail with it.
|
||||
tool: 'move_mail_booking',
|
||||
setup: async (s, app) => {
|
||||
await addedMail(s, app);
|
||||
const target = await makeTrip(orm(app), s.owner.id, {
|
||||
title: `Elsewhere ${s.n}`,
|
||||
start_date: dayFromToday(28),
|
||||
end_date: dayFromToday(32),
|
||||
});
|
||||
moveTargetOf.set(s.n, target.id);
|
||||
},
|
||||
args: (s) => ({ candidateId: mailEntry(s), trip_id: moveTarget(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'move'), body: (s) => ({ trip_id: moveTarget(s) }) },
|
||||
expect: [
|
||||
{ event: 'reservation:deleted', all: true },
|
||||
{ event: 'reservation:created', all: true, room: moveTarget },
|
||||
{ event: 'file:created', all: true, room: moveTarget },
|
||||
INBOX_CHANGED,
|
||||
],
|
||||
},
|
||||
{
|
||||
tool: 'file_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s), trip_id: s.trip.id }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'file'), body: (s) => ({ trip_id: s.trip.id }) },
|
||||
expect: [{ event: 'file:created', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
tool: 'discard_mail_booking',
|
||||
setup: waitingMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'discard') },
|
||||
expect: [INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
tool: 'undo_mail_booking',
|
||||
setup: addedMail,
|
||||
args: (s) => ({ candidateId: mailEntry(s) }),
|
||||
rest: { method: 'post', path: (s) => mailPath(s, 'undo'), body: () => ({}) },
|
||||
expect: [{ event: 'reservation:deleted', all: true }, INBOX_CHANGED],
|
||||
},
|
||||
{
|
||||
// The person's other tabs read their settings card again.
|
||||
tool: 'update_mail_import_settings',
|
||||
setup: async (_s, app) => {
|
||||
await setAppSetting(orm(app), 'mail_ingest_enabled', 'true');
|
||||
},
|
||||
args: () => ({ auto_add: false }),
|
||||
rest: { method: 'patch', path: () => '/api/mail-ingest/settings', body: () => ({ auto_add: false }) },
|
||||
expect: [{ event: 'mailInbox:settings', user: 'actor', all: true }],
|
||||
},
|
||||
],
|
||||
exempt: [],
|
||||
};
|
||||
|
||||
@@ -223,6 +223,34 @@ export const collabTrip: CaseGroup = {
|
||||
},
|
||||
expect: ['collab:message:reacted'],
|
||||
},
|
||||
{
|
||||
tool: 'create_collab_link',
|
||||
args: (s) => ({ tripId: s.trip.id, title: 'Ferry', url: 'https://example.com/ferry' }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => tripPath(s, '/collab/links'),
|
||||
body: () => ({ title: 'Ferry', url: 'https://example.com/ferry' }),
|
||||
},
|
||||
expect: ['collab:link:created'],
|
||||
},
|
||||
{
|
||||
tool: 'update_collab_link',
|
||||
needs: ['collabLink'],
|
||||
args: (s) => ({ tripId: s.trip.id, linkId: s.collabLink.id, pinned: true }),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => tripPath(s, `/collab/links/${s.collabLink.id}`),
|
||||
body: () => ({ pinned: true }),
|
||||
},
|
||||
expect: ['collab:link:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'delete_collab_link',
|
||||
needs: ['collabLink'],
|
||||
args: (s) => ({ tripId: s.trip.id, linkId: s.collabLink.id }),
|
||||
rest: { method: 'delete', path: (s) => tripPath(s, `/collab/links/${s.collabLink.id}`) },
|
||||
expect: ['collab:link:deleted'],
|
||||
},
|
||||
|
||||
// ── Files and the document store ──────────────────────────────────────
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { buildApp } from '../../../src/bootstrap';
|
||||
import { BudgetSettlements } from '../../../src/db/entities/BudgetSettlements.entity';
|
||||
import { CollabLinks } from '../../../src/db/entities/CollabLinks.entity';
|
||||
import { CollabPolls } from '../../../src/db/entities/CollabPolls.entity';
|
||||
import { DayAccommodations } from '../../../src/db/entities/DayAccommodations.entity';
|
||||
import { PackingTemplateCategories } from '../../../src/db/entities/PackingTemplateCategories.entity';
|
||||
@@ -220,7 +221,9 @@ export async function openHarness(): Promise<ParityHarness> {
|
||||
await app.init();
|
||||
const orm = app.get(MikroORM);
|
||||
await oneByOne(Object.values(ADDON_IDS), (addon) => setAddonEnabled(orm, addon, true));
|
||||
await oneByOne(['chat', 'notes', 'polls', 'whatsnext'] as const, (feature) => setCollabFeature(orm, feature, true));
|
||||
await oneByOne(['chat', 'notes', 'polls', 'links', 'whatsnext'] as const, (feature) =>
|
||||
setCollabFeature(orm, feature, true),
|
||||
);
|
||||
// The wanderer tools show only while wanderer is allowed under Tours.
|
||||
await setAppSetting(orm, 'tours_wanderer_enabled', 'true');
|
||||
// The photo search tools show only while a provider is on.
|
||||
@@ -319,6 +322,7 @@ export const NEED_KEYS: Record<Need, readonly (keyof Scene)[]> = {
|
||||
collabNote: ['collabNote'],
|
||||
collabMessage: ['collabMessage'],
|
||||
poll: ['poll'],
|
||||
collabLink: ['collabLink'],
|
||||
file: ['file'],
|
||||
collection: ['collection', 'collectionPlace'],
|
||||
journey: ['journey', 'journeyEntry'],
|
||||
@@ -443,6 +447,15 @@ const BUILDERS: Record<Need, Builder> = {
|
||||
});
|
||||
s.poll = { id: row.id };
|
||||
},
|
||||
async collabLink(s, _app, orm) {
|
||||
const id = await insertRow(orm, CollabLinks, {
|
||||
trip: s.trip.id,
|
||||
user: s.owner.id,
|
||||
title: `Ferry ${s.n}`,
|
||||
url: 'https://example.com/ferry',
|
||||
});
|
||||
s.collabLink = { id };
|
||||
},
|
||||
async file(s, _app, orm) {
|
||||
s.file = await makeTripFile(orm, s.trip.id);
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ListImportResult } from '../../../src/nest/places/places.helpers';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makeTag } from '../../helpers/factories/places';
|
||||
import { insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import type { CaseGroup, Scene } from './types';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
@@ -22,6 +23,8 @@ const dayPlanPath = (s: Scene, day: 0 | 1 | 2) => `/api/trips/${s.trip.id}/days/
|
||||
/** The per-assignment routes of the scene's assignment. */
|
||||
const assignmentPath = (s: Scene) => `/api/trips/${s.trip.id}/assignments/${s.assignment.id}`;
|
||||
const dayNotesPath = (s: Scene) => `/api/trips/${s.trip.id}/days/${s.days[0].id}/notes`;
|
||||
/** The tags the scene's trip owns. */
|
||||
const tripTagsPath = (s: Scene) => `/api/trips/${s.trip.id}/tags`;
|
||||
const onAssignment = (s: Scene) => ({ tripId: s.trip.id, assignmentId: s.assignment.id });
|
||||
|
||||
/** One waypoint, the smallest file the importer turns into a place. */
|
||||
@@ -88,9 +91,24 @@ async function boundaryOnSecondDay(s: Scene, app: INestApplication): Promise<voi
|
||||
});
|
||||
}
|
||||
|
||||
/** The tag a setup gave a scene's trip, by the scene's number. */
|
||||
const tripTagOf = new Map<number, number>();
|
||||
|
||||
/** A tag of the scene's trip, for the cases that rename or delete one. */
|
||||
async function tripTag(s: Scene, app: INestApplication): Promise<void> {
|
||||
const tag = await makeTag(app.get(MikroORM), s.owner.id, { trip: s.trip.id, name: 'Monument' });
|
||||
tripTagOf.set(s.n, tag.id);
|
||||
}
|
||||
|
||||
const tripTagId = (s: Scene): number => {
|
||||
const id = tripTagOf.get(s.n);
|
||||
if (id === undefined) throw new Error(`scene ${s.n} has no trip tag from its setup`);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* The planner: places, the day plan, days, day notes, categories, and the
|
||||
* collection places copied into a trip.
|
||||
* The planner: places and the tags their trip owns, the day plan, days, day
|
||||
* notes, categories, and the collection places copied into a trip.
|
||||
*/
|
||||
export const plan: CaseGroup = {
|
||||
name: 'plan',
|
||||
@@ -213,6 +231,30 @@ export const plan: CaseGroup = {
|
||||
},
|
||||
expect: ['place:updated', 'place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'create_trip_tag',
|
||||
args: (s) => ({ tripId: s.trip.id, name: 'Monument' }),
|
||||
rest: { method: 'post', path: tripTagsPath, body: () => ({ name: 'Monument' }) },
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'update_trip_tag',
|
||||
setup: tripTag,
|
||||
args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s), name: 'Landmark' }),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}`,
|
||||
body: () => ({ name: 'Landmark' }),
|
||||
},
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'delete_trip_tag',
|
||||
setup: tripTag,
|
||||
args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s) }),
|
||||
rest: { method: 'delete', path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}` },
|
||||
expect: ['tripTags:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'assign_place_to_day',
|
||||
needs: ['place'],
|
||||
@@ -227,6 +269,13 @@ export const plan: CaseGroup = {
|
||||
rest: { method: 'put', path: (s) => `${assignmentPath(s)}/end-day`, body: () => ({ end_day: true }) },
|
||||
expect: ['assignment:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'set_assignment_stay',
|
||||
needs: ['assignment'],
|
||||
args: (s) => ({ ...onAssignment(s), stay_minutes: 15 }),
|
||||
rest: { method: 'put', path: (s) => `${assignmentPath(s)}/stay`, body: () => ({ stay_minutes: 15 }) },
|
||||
expect: ['assignment:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'unassign_place',
|
||||
needs: ['assignment'],
|
||||
|
||||
@@ -40,6 +40,8 @@ interface Wanted {
|
||||
only: Partial<Record<Surface, Receivers>>;
|
||||
/** The surfaces limit it differently on purpose, so their receivers are not compared. */
|
||||
onlyDiffers: boolean;
|
||||
/** The trip room of this send, when it is not the case's. */
|
||||
room?: (s: Scene) => number;
|
||||
}
|
||||
|
||||
function wanted(e: Expect): Wanted {
|
||||
@@ -53,7 +55,14 @@ function wanted(e: Expect): Wanted {
|
||||
: typeof e.only === 'string'
|
||||
? { MCP: e.only, REST: e.only }
|
||||
: { MCP: e.only.mcp, REST: e.only.rest };
|
||||
return { channel: 'trip', event: e.event, all: e.all === true, only, onlyDiffers: only.MCP !== only.REST };
|
||||
return {
|
||||
channel: 'trip',
|
||||
event: e.event,
|
||||
all: e.all === true,
|
||||
only,
|
||||
onlyDiffers: only.MCP !== only.REST,
|
||||
room: e.room,
|
||||
};
|
||||
}
|
||||
|
||||
const signature = (r: { channel: string; event: string }) => `${r.channel} ${r.event}`;
|
||||
@@ -129,7 +138,7 @@ function checkSurface(surface: Surface, c: ParityCase, records: Recorded[], s: S
|
||||
);
|
||||
if (want.user === 'others') return;
|
||||
} else {
|
||||
expect(Number(r.to[0]), `sent to another room than the trip's: ${where}`).toBe(room);
|
||||
expect(Number(r.to[0]), `sent to another room than the trip's: ${where}`).toBe(want.room?.(s) ?? room);
|
||||
checkLimit(want.only[surface], r, actorId, where);
|
||||
}
|
||||
const skips = surface === 'MCP' || want.all ? undefined : REST_SOCKET;
|
||||
|
||||
@@ -36,6 +36,7 @@ export type Need =
|
||||
| 'collabNote'
|
||||
| 'collabMessage'
|
||||
| 'poll'
|
||||
| 'collabLink'
|
||||
| 'file'
|
||||
| 'guest'
|
||||
| 'member'
|
||||
@@ -100,6 +101,8 @@ export interface Scene {
|
||||
collabMessage: CollabMessageRow;
|
||||
/** Two options, open. */
|
||||
poll: IdRow;
|
||||
/** A shared link on the trip's Links panel, saved by the owner. */
|
||||
collabLink: IdRow;
|
||||
file: TripFileRow;
|
||||
/** A guest (no account) on the trip. */
|
||||
guest: UserRow;
|
||||
@@ -149,10 +152,17 @@ export type Receivers = 'actor' | 'viewers';
|
||||
* - `{ event, user }`: to users' own sockets (`broadcastToUser`). `actor` means
|
||||
* the writer is among the receivers (REST leaves out the requesting socket
|
||||
* unless `all` is set too), `others` that only other users receive it.
|
||||
* - `{ event, room }`: to another trip room than the case's, for a write that
|
||||
* touches two trips (a booking moved from one trip into another).
|
||||
*/
|
||||
export type Expect =
|
||||
| TrekWsTripEventName
|
||||
| { event: TrekWsTripEventName; all?: true; only?: Receivers | { rest: Receivers; mcp: Receivers } }
|
||||
| {
|
||||
event: TrekWsTripEventName;
|
||||
all?: true;
|
||||
only?: Receivers | { rest: Receivers; mcp: Receivers };
|
||||
room?: (s: Scene) => number;
|
||||
}
|
||||
| { event: TrekWsUserEventName; user: 'actor' | 'others'; all?: true };
|
||||
|
||||
/** The REST twin of a tool, called as the same user with X-Socket-Id 'sock-rest'. */
|
||||
|
||||
@@ -245,6 +245,49 @@ describe('Three-tier packing sharing (#858)', () => {
|
||||
expect(res.body.item.contributors.map((c: any) => c.user_id)).toContain(helper.id);
|
||||
});
|
||||
|
||||
it('PACK-3T-004b — a member puts someone else down as the bringer, and takes the owner off again (#3098)', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: helper } = createUser(testDb);
|
||||
const { user: stranger } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, helper.id);
|
||||
const created = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ name: 'Stove', visibility: 'personal' });
|
||||
const id = created.body.item.id;
|
||||
await request(app)
|
||||
.put(`/api/trips/${trip.id}/packing/${id}/sharing`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ visibility: 'common' });
|
||||
|
||||
const assigned = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: helper.id });
|
||||
expect(assigned.status).toBe(201);
|
||||
expect(assigned.body.item.contributors.map((c: { user_id: number }) => c.user_id)).toEqual([helper.id]);
|
||||
|
||||
const outsider = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: stranger.id });
|
||||
expect(outsider.status).toBe(404);
|
||||
|
||||
const bad = await request(app)
|
||||
.post(`/api/trips/${trip.id}/packing/${id}/contributors`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ user_id: 'x' });
|
||||
expect(bad.status).toBe(400);
|
||||
|
||||
const ownerOff = await request(app)
|
||||
.delete(`/api/trips/${trip.id}/packing/${id}/contributors/${owner.id}`)
|
||||
.set('Cookie', authCookie(helper.id));
|
||||
expect(ownerOff.status).toBe(200);
|
||||
expect(ownerOff.body.item.owner_id).toBeNull();
|
||||
expect(ownerOff.body.item.contributors.map((c: { user_id: number }) => c.user_id)).toEqual([helper.id]);
|
||||
});
|
||||
|
||||
it('PACK-3T-005 — sharing can only be changed by the owner', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
|
||||
@@ -1059,6 +1059,8 @@ describe('Copy trip with data', () => {
|
||||
place: place.id,
|
||||
order_index: 0,
|
||||
notes: 'Visit in morning',
|
||||
// #3092: the visit's own stay, apart from the place's duration
|
||||
stay_minutes: 90,
|
||||
});
|
||||
|
||||
// Accommodation spanning days 0→1
|
||||
@@ -1103,6 +1105,7 @@ describe('Copy trip with data', () => {
|
||||
// Assignment copied
|
||||
const newAssignments = await findRows(orm, DayAssignments, { day: { trip: newId } });
|
||||
expect(newAssignments).toHaveLength(1);
|
||||
expect(newAssignments[0].stay_minutes).toBe(90);
|
||||
|
||||
// Accommodation copied
|
||||
const newAccom = await findRows(orm, DayAccommodations, { trip: newId });
|
||||
|
||||
@@ -28,7 +28,16 @@ vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([{ date: '2025-01-01', name: "New Year's Day", countryCode: 'DE' }]),
|
||||
json: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
date: '2025-01-01',
|
||||
name: "New Year's Day",
|
||||
countryCode: 'DE',
|
||||
nationalHoliday: true,
|
||||
subdivisionCodes: null,
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -448,17 +457,6 @@ describe('Vacay stats restrictions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay holidays error path', () => {
|
||||
it('VACAY-035 — GET /holidays/:year/:country returns 502 when external API fetch fails', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// Use an unusual country/year to avoid cache hits from other tests
|
||||
vi.mocked(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2099/ZZ').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay color restriction', () => {
|
||||
it('VACAY-036 — PUT /color with target_user_id not in plan returns 403', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
@@ -473,20 +471,6 @@ describe('Vacay color restriction', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay holidays success path', () => {
|
||||
it('VACAY-037 — GET /holidays/:year/:country returns data when fetch succeeds', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
// Use unique year/country to avoid cache from other tests
|
||||
vi.mocked(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([{ date: '2025-05-01', name: 'Labour Day', countryCode: 'AT' }]),
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2025/AT').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay toggle entry for plan member', () => {
|
||||
it('VACAY-038 — POST /entries/toggle with target_user_id in plan toggles their entry', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
@@ -647,3 +631,41 @@ describe('Vacay read-only calendar shares', () => {
|
||||
expect(res.body.error).toBe('Already shared');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vacay public holidays', () => {
|
||||
it('VACAY-035 — returns 502 when the external API fetch fails', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2099/ZZ').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(502);
|
||||
});
|
||||
|
||||
it('VACAY-037 — adapts a Nager v4 record when the external API succeeds', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
date: '2025-05-01',
|
||||
name: 'Labour Day',
|
||||
nationalHoliday: true,
|
||||
subdivisionCodes: null,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
const res = await request(app).get('/api/addons/vacay/holidays/2087/AT').set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual([
|
||||
{
|
||||
date: '2025-05-01',
|
||||
name: 'Labour Day',
|
||||
localName: 'Labour Day',
|
||||
global: true,
|
||||
counties: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
deriveHttpBoot,
|
||||
deriveKitinerary,
|
||||
deriveMailIngest,
|
||||
deriveServices,
|
||||
deriveStorage,
|
||||
deriveTransit,
|
||||
@@ -234,6 +235,13 @@ describe('derivePlugins', () => {
|
||||
});
|
||||
|
||||
describe('deriveIntegrations', () => {
|
||||
it('reads FLIGHT_LIVE_ENABLED as the setting spells it, unset or unparseable as no word at all', () => {
|
||||
expect(deriveIntegrations({}).flightLiveEnabled).toBeUndefined();
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: 'off' }).flightLiveEnabled).toBe('false');
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: ' YES ' }).flightLiveEnabled).toBe('true');
|
||||
expect(deriveIntegrations({ FLIGHT_LIVE_ENABLED: 'maybe' }).flightLiveEnabled).toBeUndefined();
|
||||
});
|
||||
|
||||
it('pins unsplash trim, nominatim trim + default, overpass timeout', () => {
|
||||
expect(deriveIntegrations({ UNSPLASH_ACCESS_KEY: ' key ' }).unsplashAccessKey).toBe('key');
|
||||
expect(deriveIntegrations({}).nominatimUrl).toBe('https://nominatim.openstreetmap.org');
|
||||
@@ -292,6 +300,23 @@ describe('deriveKitinerary (kitineraryConfig token)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveMailIngest (mailIngestConfig token)', () => {
|
||||
it('leaves every value unset unless its variable holds one, trimmed', () => {
|
||||
expect(Object.values(deriveMailIngest({}))).toEqual(Array(9).fill(null));
|
||||
expect(deriveMailIngest({ MAIL_INGEST_IMAP_HOST: ' ', MAIL_INGEST_IMAP_PASS: ' s3cret ' })).toMatchObject({
|
||||
imapHost: null,
|
||||
imapPass: 's3cret',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the transport and the encryption in lower case', () => {
|
||||
expect(deriveMailIngest({ MAIL_INGEST_TRANSPORT: 'IMAP', MAIL_INGEST_IMAP_TLS: 'StartTLS' })).toMatchObject({
|
||||
transport: 'imap',
|
||||
imapTls: 'starttls',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveServices (servicesConfig token)', () => {
|
||||
it('registers by itself unless TREK_SERVICES says off, and any value but auto is off', () => {
|
||||
expect(deriveServices({}).mode).toBe('auto');
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* `Migration20200101046370_a_deleted_chat_message_keeps_no_text`: a message deleted
|
||||
* before the release loses its text; a live message keeps its own.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101046370_a_deleted_chat_message_keeps_no_text';
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
const names = await pendingNames(orm);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(orm, names[index - 1]);
|
||||
return orm;
|
||||
}
|
||||
|
||||
describe('a deleted chat message keeps no text', () => {
|
||||
it('CHAT-DELETED-TEXT-001: blanks the text of deleted messages and leaves live ones alone', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
|
||||
);
|
||||
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Kyoto')");
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO collab_messages (id, trip_id, user_id, text, deleted) VALUES (1, 10, 1, 'meet at 8', 0), (2, 10, 1, 'my door code is 4711', 1)",
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
const rows = await rawQuery<{ id: number; text: string; deleted: number }>(
|
||||
orm,
|
||||
'SELECT id, text, deleted FROM collab_messages ORDER BY id',
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ id: 1, text: 'meet at 8', deleted: 0 },
|
||||
{ id: 2, text: '', deleted: 1 },
|
||||
]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -57,14 +57,16 @@ describe('ALL_ENTITIES', () => {
|
||||
* + trek_photo_signals, what a photo's pixels say, for picking photos for a book
|
||||
* + journey_book_revisions, the books a whole-book design replaced, for its undo
|
||||
* + trip_member_removals, who another member took off a trip, so its invite link refuses them
|
||||
* + assistant_attachments, the files attached in the trip chat, kept with their conversation)
|
||||
* + assistant_attachments, the files attached in the trip chat, kept with their conversation
|
||||
* + mail_ingest_addresses, _prefs, _cursor, _messages and _candidates, the forwarded
|
||||
* booking mails, the bookings read from them and the switches and addresses behind them)
|
||||
* is registered, and no two share a class name (a silent duplicate would
|
||||
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
|
||||
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
|
||||
* which de-duplicates by class name).
|
||||
*/
|
||||
it('ENT-003: exactly 167 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(167);
|
||||
it('ENT-003: exactly 173 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(173);
|
||||
const names = ALL_ENTITIES.map((s) => s.meta.className);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
@@ -61,7 +61,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
// (an attached file is only ever written whole, by the turn it was attached in).
|
||||
// + storage_reclaim_marks: category, key, first_seen_at, size (a mark is only ever written whole, by the reclaim pass).
|
||||
// + storage_release_queue: category, key, due_at (a queued release is only ever written whole, by the release queue).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 611;
|
||||
// + flight_live_states: callsign, service_date, origin, destination (a flight's state is always found and
|
||||
// written by its key).
|
||||
// + mail_ingest_addresses: id, token_hash, token_enc, user_id; mail_ingest_prefs: id, user_id; mail_ingest_cursor:
|
||||
// id, transport, mailbox; mail_ingest_messages: id, transport, dedupe_hash, user_id, size; mail_ingest_candidates:
|
||||
// id, message_id, user_id (each row is written whole by the mail import, which always knows all of them).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 632;
|
||||
|
||||
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
|
||||
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* `Migration20200101046380_ireland_gained_its_counties` (#2922): the Atlas ships
|
||||
* Ireland's 26 counties instead of its four provinces. Cached place regions are
|
||||
* cleared, hand-marked provinces stay, county names under stale codes take the county
|
||||
* code, and a hidden province hides its counties.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101046380_ireland_gained_its_counties';
|
||||
const LEINSTER = [
|
||||
'IE-CW',
|
||||
'IE-D',
|
||||
'IE-KE',
|
||||
'IE-KK',
|
||||
'IE-LD',
|
||||
'IE-LH',
|
||||
'IE-LS',
|
||||
'IE-MH',
|
||||
'IE-OY',
|
||||
'IE-WH',
|
||||
'IE-WW',
|
||||
'IE-WX',
|
||||
];
|
||||
|
||||
let orm: MikroORM;
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const o = await createMigrationOrm();
|
||||
const names = await pendingNames(o);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(o, names[index - 1]);
|
||||
return o;
|
||||
}
|
||||
|
||||
async function seedUsers(): Promise<void> {
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO users (id, username, email, password_hash) VALUES (1, 'one', 'one@test', 'x'), (2, 'two', 'two@test', 'x')`,
|
||||
);
|
||||
}
|
||||
|
||||
const visited = (userId: number) =>
|
||||
rawQuery<{ region_code: string; region_name: string; country_code: string }>(
|
||||
orm,
|
||||
'SELECT region_code, region_name, country_code FROM visited_regions WHERE user_id = ? ORDER BY region_code',
|
||||
[userId],
|
||||
);
|
||||
|
||||
const hidden = async (userId: number) =>
|
||||
(
|
||||
await rawQuery<{ region_code: string }>(
|
||||
orm,
|
||||
'SELECT region_code FROM hidden_regions WHERE user_id = ? ORDER BY region_code',
|
||||
[userId],
|
||||
)
|
||||
).map((r) => r.region_code);
|
||||
|
||||
afterEach(async () => {
|
||||
await orm?.close(true);
|
||||
});
|
||||
|
||||
describe('Ireland gained its counties', () => {
|
||||
it('IE-COUNTIES-001: clears the cached Irish place regions and leaves other countries cached', async () => {
|
||||
orm = await ormBeforeTarget();
|
||||
await seedUsers();
|
||||
await rawExec(orm, `INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'Isles')`);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO places (id, trip_id, name, lat, lng) VALUES (1, 1, 'Dublin', 53.34, -6.25), (2, 1, 'Belfast', 54.6, -5.93)`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES
|
||||
(1, 'IE', 'IE-L', 'Leinster'), (2, 'GB', 'GB-BELFAST', 'Belfast')`,
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await rawQuery(orm, 'SELECT place_id, region_code FROM place_regions ORDER BY place_id')).toEqual([
|
||||
{ place_id: 2, region_code: 'GB-BELFAST' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('IE-COUNTIES-002: keeps a marked province and a marked county, and moves a county name onto its code', async () => {
|
||||
orm = await ormBeforeTarget();
|
||||
await seedUsers();
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES
|
||||
(1, 'IE-L', 'Leinster', 'IE'),
|
||||
(1, 'IE-KY', 'Kerry', 'IE'),
|
||||
(1, 'IE-COR', 'County Cork', 'IE'),
|
||||
(1, 'IE-GALWAY', 'Co. Galway', 'ie'),
|
||||
(1, 'FR-IDF', 'Ile-de-France', 'FR')`,
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await visited(1)).toEqual([
|
||||
{ region_code: 'FR-IDF', region_name: 'Ile-de-France', country_code: 'FR' },
|
||||
{ region_code: 'IE-CO', region_name: 'Cork', country_code: 'IE' },
|
||||
{ region_code: 'IE-G', region_name: 'Galway', country_code: 'ie' },
|
||||
{ region_code: 'IE-KY', region_name: 'Kerry', country_code: 'IE' },
|
||||
{ region_code: 'IE-L', region_name: 'Leinster', country_code: 'IE' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('IE-COUNTIES-003: drops a stale row whose county the user already holds, never touching another user', async () => {
|
||||
orm = await ormBeforeTarget();
|
||||
await seedUsers();
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO visited_regions (user_id, region_code, region_name, country_code) VALUES
|
||||
(1, 'IE-D', 'Dublin', 'IE'),
|
||||
(1, 'IE-DUB', 'County Dublin', 'IE'),
|
||||
(1, 'IE-DN', 'dublin', 'IE'),
|
||||
(2, 'IE-DUB', 'County Dublin', 'IE')`,
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await visited(1)).toEqual([{ region_code: 'IE-D', region_name: 'Dublin', country_code: 'IE' }]);
|
||||
expect(await visited(2)).toEqual([{ region_code: 'IE-D', region_name: 'Dublin', country_code: 'IE' }]);
|
||||
});
|
||||
|
||||
it('IE-COUNTIES-004: a hidden province hides each of its counties, once, and stays hidden itself', async () => {
|
||||
orm = await ormBeforeTarget();
|
||||
await seedUsers();
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO hidden_regions (user_id, region_code, country_code) VALUES
|
||||
(1, 'IE-L', 'IE'),
|
||||
(1, 'IE-D', 'IE'),
|
||||
(2, 'IE-U', 'IE'),
|
||||
(2, 'FR-IDF', 'FR')`,
|
||||
);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await hidden(1)).toEqual([...LEINSTER, 'IE-L'].sort());
|
||||
expect(await hidden(2)).toEqual(['FR-IDF', 'IE-CN', 'IE-DL', 'IE-MN', 'IE-U']);
|
||||
});
|
||||
});
|
||||
@@ -104,6 +104,14 @@ const UNNUMBERED = [
|
||||
'Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes',
|
||||
'Migration20200101046350_a_place_lies_on_the_real_world',
|
||||
'Migration20200101046360_a_new_install_starts_with_more_addons_on',
|
||||
'Migration20200101046370_a_deleted_chat_message_keeps_no_text',
|
||||
'Migration20200101046380_ireland_gained_its_counties',
|
||||
'Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only',
|
||||
'Migration20200101046400_a_booked_flight_shows_where_it_is',
|
||||
'Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip',
|
||||
'Migration20200101046420_a_visit_keeps_its_own_stay',
|
||||
'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders',
|
||||
'Migration20200101046440_a_trip_owns_its_tags',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* `Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders`:
|
||||
* `mail_ingest_cursor` is rebuilt so the pause notice job can keep its row
|
||||
* (`transport = 'notice'`), without losing a reader's position or lease; an
|
||||
* unknown transport is still refused and a reader stays unique per mailbox.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders';
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
const names = await pendingNames(orm);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(orm, names[index - 1]);
|
||||
return orm;
|
||||
}
|
||||
|
||||
describe('Mail ingest cursor notice migration', () => {
|
||||
it('MICURMIG-001: keeps every reader as it was and lets the notice job take its row', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO mail_ingest_cursor
|
||||
(id, transport, mailbox, uid_validity, last_uid, last_ok_at, last_error, lease_owner, lease_until)
|
||||
VALUES (4, 'imap', 'INBOX', 7, 42, '2026-11-01 10:00:00', 'timeout', 'a', '2026-11-01 10:05:00')`,
|
||||
);
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')"),
|
||||
).rejects.toThrow(/CHECK/);
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await rawQuery(orm, 'SELECT * FROM mail_ingest_cursor')).toEqual([
|
||||
{
|
||||
id: 4,
|
||||
transport: 'imap',
|
||||
mailbox: 'INBOX',
|
||||
uid_validity: 7,
|
||||
last_uid: 42,
|
||||
last_ok_at: '2026-11-01 10:00:00',
|
||||
last_error: 'timeout',
|
||||
lease_owner: 'a',
|
||||
lease_until: '2026-11-01 10:05:00',
|
||||
},
|
||||
]);
|
||||
await rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')");
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('notice', 'paused')"),
|
||||
).rejects.toThrow(/UNIQUE/);
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO mail_ingest_cursor (transport, mailbox) VALUES ('webhook', '')"),
|
||||
).rejects.toThrow(/CHECK/);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -119,6 +119,13 @@ describe('migrate-encryption.ts app_settings parity', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// A forwarding address shows its token through token_enc; a stored mail is sealed in raw_eml_enc.
|
||||
it('ROTPAR-016: rotates the address tokens and stored mails of the mail import', () => {
|
||||
const section = script.slice(script.indexOf('--- mail_ingest:'), script.indexOf('--- addons:'));
|
||||
expect(section).toContain("['mail_ingest_addresses', 'token_enc']");
|
||||
expect(section).toContain("['mail_ingest_messages', 'raw_eml_enc']");
|
||||
});
|
||||
|
||||
it('ROTPAR-004: rotates every storage.backends secret field for s3', () => {
|
||||
const fields = storageSecretFields('s3');
|
||||
expect(fields.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* `CollectionsRepository`: the order of a list's places and the pages
|
||||
* list_collection_places reads it in (#2647). getCollection (listPlaceRows)
|
||||
* and a page order the same way, sort_order, then created_at, then id, so two
|
||||
* places saved in the same second keep one order; a page filters by status,
|
||||
* label or "no label" and goes on after a position, not an offset.
|
||||
* COLL-REPO-001 to COLL-REPO-005.
|
||||
*/
|
||||
import { CollectionLabels } from '../../../../src/db/entities/CollectionLabels.entity';
|
||||
import type { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
|
||||
import { Collections } from '../../../../src/db/entities/Collections.entity';
|
||||
import type {
|
||||
CollectionPlacePageRow,
|
||||
CollectionsRepository,
|
||||
} from '../../../../src/db/repositories/Collections.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { labelCollectionPlace, makeCollection, makeCollectionPlace } from '../../../helpers/factories/collections';
|
||||
import { createRow } from '../../../helpers/factories/rows';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
import type { EntityData } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: CollectionsRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(Collections);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const SAME_SECOND = '2026-05-01 10:00:00';
|
||||
|
||||
/**
|
||||
* A list of five places: two saved in the same second at position 0, one saved
|
||||
* earlier at position 0, one at position 1 and one whose position was never
|
||||
* written (it reads as 0, after the earlier one by its created_at).
|
||||
*/
|
||||
async function seedList() {
|
||||
const { user } = await makeUser(t);
|
||||
const list = await makeCollection(t, user.id, { name: 'Paris' });
|
||||
const place = (name: string, overrides: EntityData<CollectionPlaces>) =>
|
||||
makeCollectionPlace(t, list.id, user.id, { name, ...overrides });
|
||||
const later = await place('Later', { sort_order: 1, created_at: '2026-04-01 09:00:00' });
|
||||
const tieA = await place('Tie A', { sort_order: 0, created_at: SAME_SECOND, status: 'want' });
|
||||
const tieB = await place('Tie B', { sort_order: 0, created_at: SAME_SECOND });
|
||||
const early = await place('Early', { sort_order: 0, created_at: '2026-03-01 08:00:00', status: 'want' });
|
||||
const unplaced = await place('Unplaced', { sort_order: null, created_at: '2026-03-15 08:00:00' });
|
||||
return { user, list, ids: { later: later.id, tieA: tieA.id, tieB: tieB.id, early: early.id, unplaced: unplaced.id } };
|
||||
}
|
||||
|
||||
const names = (rows: Array<Pick<CollectionPlacePageRow, 'name'>>) => rows.map((row) => row.name);
|
||||
|
||||
describe('CollectionsRepository: the order of a list', () => {
|
||||
it('COLL-REPO-001: getCollection orders by position, then saving time, then id', async () => {
|
||||
const { list } = await seedList();
|
||||
const rows = await repo.listPlaceRows(list.id);
|
||||
expect(names(rows)).toEqual(['Early', 'Unplaced', 'Tie A', 'Tie B', 'Later']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CollectionsRepository: a page of a list (#2647)', () => {
|
||||
it('COLL-REPO-002: a page holds the list in that same order and goes on after the position it names', async () => {
|
||||
const { list, ids } = await seedList();
|
||||
const first = await repo.listPlacePage(list.id, {}, null, 3);
|
||||
expect(names(first)).toEqual(['Early', 'Unplaced', 'Tie A']);
|
||||
// The position a page goes on from: the missing sort_order reads as 0.
|
||||
expect(first[1]).toMatchObject({ id: ids.unplaced, sort_key: 0, created_key: '2026-03-15 08:00:00' });
|
||||
|
||||
const tieA = first[2];
|
||||
const rest = await repo.listPlacePage(
|
||||
list.id,
|
||||
{},
|
||||
{ sortOrder: tieA.sort_key, createdAt: tieA.created_key, id: tieA.id },
|
||||
3,
|
||||
);
|
||||
expect(names(rest)).toEqual(['Tie B', 'Later']);
|
||||
expect(await repo.countPlacePage(list.id, {})).toBe(5);
|
||||
});
|
||||
|
||||
it('COLL-REPO-003: a page carries the fields an agent names a place by', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const list = await makeCollection(t, user.id);
|
||||
await makeCollectionPlace(t, list.id, user.id, {
|
||||
name: 'Septime',
|
||||
address: '80 Rue de Charonne',
|
||||
google_place_id: 'ChIJseptime',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
});
|
||||
const [row] = await repo.listPlacePage(list.id, {}, null, 10);
|
||||
expect(row).toMatchObject({
|
||||
name: 'Septime',
|
||||
status: 'idea',
|
||||
address: '80 Rue de Charonne',
|
||||
lat: 48.8566,
|
||||
lng: 2.3522,
|
||||
google_place_id: 'ChIJseptime',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
});
|
||||
});
|
||||
|
||||
it('COLL-REPO-004: filters by status and by label, and counts what the filter matches', async () => {
|
||||
const { list, ids } = await seedList();
|
||||
const label = await createRow(t, CollectionLabels, { collection: list.id, name: 'Food' });
|
||||
await labelCollectionPlace(t, ids.tieB, label.id);
|
||||
await labelCollectionPlace(t, ids.later, label.id);
|
||||
|
||||
expect(names(await repo.listPlacePage(list.id, { status: 'want' }, null, 10))).toEqual(['Early', 'Tie A']);
|
||||
expect(await repo.countPlacePage(list.id, { status: 'want' })).toBe(2);
|
||||
expect(names(await repo.listPlacePage(list.id, { labelId: label.id }, null, 10))).toEqual(['Tie B', 'Later']);
|
||||
expect(await repo.countPlacePage(list.id, { labelId: label.id })).toBe(2);
|
||||
expect(names(await repo.listPlacePage(list.id, { unlabeled: true }, null, 10))).toEqual([
|
||||
'Early',
|
||||
'Unplaced',
|
||||
'Tie A',
|
||||
]);
|
||||
expect(await repo.countPlacePage(list.id, { unlabeled: true, status: 'want' })).toBe(2);
|
||||
});
|
||||
|
||||
it('COLL-REPO-005: a place labelled after its page was read does not move the next page of unlabelled ones', async () => {
|
||||
const { list, ids } = await seedList();
|
||||
const label = await createRow(t, CollectionLabels, { collection: list.id, name: 'Done' });
|
||||
const first = await repo.listPlacePage(list.id, { unlabeled: true }, null, 2);
|
||||
expect(names(first)).toEqual(['Early', 'Unplaced']);
|
||||
await labelCollectionPlace(t, ids.early, label.id);
|
||||
await labelCollectionPlace(t, ids.unplaced, label.id);
|
||||
|
||||
const last = first[1];
|
||||
const next = await repo.listPlacePage(
|
||||
list.id,
|
||||
{ unlabeled: true },
|
||||
{ sortOrder: last.sort_key, createdAt: last.created_key, id: last.id },
|
||||
2,
|
||||
);
|
||||
expect(names(next)).toEqual(['Tie A', 'Tie B']);
|
||||
});
|
||||
});
|
||||
@@ -1047,6 +1047,31 @@ describe('DayAssignmentsRepository.insertAssignmentCopy (TP49)', () => {
|
||||
accommodation_id: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("ASSIGNREPO-048: carries the visit's own stay_minutes, null when none is given (#3092)", async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const copy = {
|
||||
day_id: day.id,
|
||||
place_id: place.id,
|
||||
order_index: 0,
|
||||
notes: null,
|
||||
reservation_status: null,
|
||||
reservation_notes: null,
|
||||
reservation_datetime: null,
|
||||
assignment_time: null,
|
||||
assignment_end_time: null,
|
||||
end_day: 0,
|
||||
};
|
||||
|
||||
const withStay = await assignments.insertAssignmentCopy({ ...copy, stay_minutes: 90 });
|
||||
const without = await assignments.insertAssignmentCopy(copy);
|
||||
|
||||
expect(await assignmentCols(withStay, 'stay_minutes')).toEqual({ stay_minutes: 90 });
|
||||
expect(await assignmentCols(without, 'stay_minutes')).toEqual({ stay_minutes: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('DayAssignmentsRepository.setAccommodation (TP57)', () => {
|
||||
@@ -1079,7 +1104,7 @@ const LEGACY_LIST_ROADTRIP_VISITS = `
|
||||
SELECT a.id, a.day_id, a.order_index, a.place_id, p.name, p.lat, p.lng,
|
||||
COALESCE(a.assignment_time, p.place_time) AS time,
|
||||
COALESCE(a.assignment_end_time, p.end_time) AS end_time,
|
||||
p.duration_minutes, a.end_day,
|
||||
COALESCE(a.stay_minutes, p.duration_minutes) AS duration_minutes, a.end_day,
|
||||
a.leg_transport_mode, a.incoming_leg_transport_mode, p.stop_type, p.fill_percent,
|
||||
a.accommodation_id, stay.id AS stay_id, stay.check_in, stay.check_out, checkout.day_number AS checkout_day
|
||||
FROM day_assignments a
|
||||
@@ -1171,6 +1196,26 @@ describe('DayAssignmentsRepository.listRoadtripVisits (RPL2, roadtrip-plan.servi
|
||||
});
|
||||
});
|
||||
|
||||
it('ASSIGNREPO-036: two visits of one place keep their own stay, an unset one reads the place (#3092)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id, { name: 'Viewpoint' });
|
||||
await updateRows(t, Places, { id: place.id }, { duration_minutes: 45 });
|
||||
const stopped = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
|
||||
const passed = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
|
||||
|
||||
await withRequestContext(t.orm, () => assignments.setStayMinutes(passed.id, 0));
|
||||
|
||||
const visits = await assignments.listRoadtripVisits(trip.id);
|
||||
expect(visits.map((v) => [v.id, v.duration_minutes])).toEqual([
|
||||
[stopped.id, 45],
|
||||
[passed.id, 0],
|
||||
]);
|
||||
expect(await assignmentCols(stopped.id, 'stay_minutes')).toEqual({ stay_minutes: null });
|
||||
expect((await findRow(t, Places, { id: place.id }))?.duration_minutes).toBe(45);
|
||||
});
|
||||
|
||||
it('ASSIGNREPO-033: empty array for a trip with no assignments', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* FlightLiveStatesRepository: the stored state of a flight per callsign and
|
||||
* day, and the reads of flight bookings, endpoints, days and travellers the
|
||||
* live flight status builds its legs from. FLREPO-001 to FLREPO-007.
|
||||
*/
|
||||
import { FlightLiveStates } from '../../../../src/db/entities/FlightLiveStates.entity';
|
||||
import type {
|
||||
FlightLiveStatesRepository,
|
||||
FlightLiveStateWrite,
|
||||
} from '../../../../src/db/repositories/FlightLiveStates.repository';
|
||||
import type { DbTimestamp } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import {
|
||||
addReservationTraveler,
|
||||
makeReservation,
|
||||
makeReservationEndpoint,
|
||||
} from '../../../helpers/factories/reservations';
|
||||
import { findRows } from '../../../helpers/factories/rows';
|
||||
import { addTripMember, makeDay, makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: FlightLiveStatesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(FlightLiveStates);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
function state(overrides: Partial<FlightLiveStateWrite> = {}): FlightLiveStateWrite {
|
||||
return {
|
||||
callsign: 'DLH716',
|
||||
service_date: '2026-07-01',
|
||||
origin: 'FRA',
|
||||
destination: 'HND',
|
||||
phase: 'airborne',
|
||||
departed_at: '2026-07-01 11:52:00' as DbTimestamp,
|
||||
landed_at: null,
|
||||
lat: 55.1,
|
||||
lng: 60.2,
|
||||
altitude_ft: 36000,
|
||||
ground_speed_kt: 480,
|
||||
track_deg: 51,
|
||||
vertical_rate_fpm: 0,
|
||||
on_ground: 0,
|
||||
registration: 'D-AIXA',
|
||||
aircraft_type: 'A359',
|
||||
source: 'adsb.lol',
|
||||
first_seen_at: '2026-07-01 11:40:00' as DbTimestamp,
|
||||
last_seen_at: '2026-07-01 14:00:00' as DbTimestamp,
|
||||
fetched_at: '2026-07-01 14:00:01' as DbTimestamp,
|
||||
next_poll_at: '2026-07-01 14:03:01' as DbTimestamp,
|
||||
fail_count: 0,
|
||||
departed_notified: 1,
|
||||
landed_notified: 0,
|
||||
delay_notified: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('FlightLiveStatesRepository: states', () => {
|
||||
it('FLREPO-001: writes a whole state and replaces it under the same key', async () => {
|
||||
await repo.saveState(state());
|
||||
await repo.saveState(state({ phase: 'landed', landed_at: '2026-07-01 23:10:00' as DbTimestamp, lat: 35.5 }));
|
||||
await repo.saveState(state({ service_date: '2026-07-02', phase: 'scheduled' }));
|
||||
await repo.saveState(state({ callsign: 'BAW12' }));
|
||||
|
||||
const rows = await repo.findForCallsigns(['DLH716']);
|
||||
expect(rows.map((r) => [r.service_date, r.phase, r.landed_at, r.lat]).sort()).toEqual([
|
||||
['2026-07-01', 'landed', '2026-07-01 23:10:00', 35.5],
|
||||
['2026-07-02', 'scheduled', null, 55.1],
|
||||
]);
|
||||
expect(rows.find((r) => r.service_date === '2026-07-01')).toMatchObject({
|
||||
registration: 'D-AIXA',
|
||||
departed_notified: 1,
|
||||
next_poll_at: '2026-07-01 14:03:01',
|
||||
});
|
||||
expect(await repo.findForCallsigns([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-001b: two sectors of one flight number on one day are two states', async () => {
|
||||
await repo.saveState(state({ callsign: 'DLH754', origin: 'FRA', destination: 'BOM' }));
|
||||
await repo.saveState(state({ callsign: 'DLH754', origin: 'BOM', destination: 'SIN', phase: 'scheduled' }));
|
||||
const rows = await repo.findForCallsigns(['DLH754']);
|
||||
expect(rows.map((r) => [r.origin, r.destination, r.phase]).sort()).toEqual([
|
||||
['BOM', 'SIN', 'scheduled'],
|
||||
['FRA', 'BOM', 'airborne'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLREPO-002: drops the states of flights that departed before a day', async () => {
|
||||
await repo.saveState(state({ service_date: '2026-05-30' }));
|
||||
await repo.saveState(state({ service_date: '2026-06-01' }));
|
||||
expect(await repo.deleteBefore('2026-06-01')).toBe(1);
|
||||
expect((await findRows(t, FlightLiveStates)).map((r) => r.service_date)).toEqual(['2026-06-01']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FlightLiveStatesRepository: bookings', () => {
|
||||
it('FLREPO-003: the flight bookings of one trip with the trip title, nothing of other types or trips', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id, { title: 'Japan' });
|
||||
const other = await makeTrip(t, user.id);
|
||||
const flight = await makeReservation(t, trip.id, {
|
||||
title: 'FRA to HND',
|
||||
type: 'flight',
|
||||
metadata: '{"flight_number":"LH 716"}',
|
||||
reservation_time: '2026-07-01T13:40',
|
||||
});
|
||||
await makeReservation(t, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await makeReservation(t, other.id, { title: 'Elsewhere', type: 'flight' });
|
||||
|
||||
expect(await repo.listFlightBookingsForTrip(trip.id)).toEqual([
|
||||
{
|
||||
id: flight.id,
|
||||
trip_id: trip.id,
|
||||
trip_title: 'Japan',
|
||||
metadata: '{"flight_number":"LH 716"}',
|
||||
day_id: null,
|
||||
end_day_id: null,
|
||||
reservation_time: '2026-07-01T13:40',
|
||||
reservation_end_time: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('FLREPO-004: the poll candidates skip archived trips and trips whose dates lie outside the span', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const current = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05' });
|
||||
const undated = await makeTrip(t, user.id);
|
||||
const past = await makeTrip(t, user.id, { start_date: '2026-05-01', end_date: '2026-05-03' });
|
||||
const future = await makeTrip(t, user.id, { start_date: '2026-09-01', end_date: '2026-09-03' });
|
||||
const archived = await makeTrip(t, user.id, { start_date: '2026-06-28', end_date: '2026-07-05', is_archived: 1 });
|
||||
await [current, undated, past, future, archived].reduce(async (previous, trip) => {
|
||||
await previous;
|
||||
await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
}, Promise.resolve());
|
||||
const rows = await repo.listFlightBookingsBetween('2026-06-29', '2026-07-03');
|
||||
expect(rows.map((r) => r.trip_id).sort((a, b) => a - b)).toEqual([current.id, undated.id].sort((a, b) => a - b));
|
||||
});
|
||||
|
||||
it('FLREPO-005: the endpoints of the bookings in their order, and none for no bookings', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
await makeReservationEndpoint(t, flight.id, { role: 'to', sequence: 1, code: 'HND', name: 'Haneda (HND)' });
|
||||
await makeReservationEndpoint(t, flight.id, {
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
code: 'FRA',
|
||||
name: 'Frankfurt (FRA)',
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '13:40',
|
||||
});
|
||||
const endpoints = await repo.listEndpoints([flight.id]);
|
||||
expect(endpoints.map((e) => [e.sequence, e.code])).toEqual([
|
||||
[0, 'FRA'],
|
||||
[1, 'HND'],
|
||||
]);
|
||||
expect(endpoints[0]).toMatchObject({
|
||||
reservation_id: flight.id,
|
||||
role: 'from',
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2026-07-01',
|
||||
local_time: '13:40',
|
||||
});
|
||||
expect(await repo.listEndpoints([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-006: the dates of trip days, leaving out a day without one', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const dated = await makeDay(t, trip.id, { day_number: 1, date: '2026-07-01' });
|
||||
const undated = await makeDay(t, trip.id, { day_number: 2, date: null });
|
||||
expect(await repo.listDayDates([dated.id, undated.id])).toEqual([{ id: dated.id, date: '2026-07-01' }]);
|
||||
expect(await repo.listDayDates([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('FLREPO-007: the travellers put on a booking who still belong to the trip, never a removed member', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: friend } = await makeUser(t);
|
||||
const { user: removed } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
await addTripMember(t, trip.id, friend.id);
|
||||
const flight = await makeReservation(t, trip.id, { title: 'Flight', type: 'flight' });
|
||||
expect(await repo.listTravelerIds(flight.id)).toEqual([]);
|
||||
await addReservationTraveler(t, flight.id, friend.id);
|
||||
await addReservationTraveler(t, flight.id, user.id);
|
||||
// On the traveller list from before, but no longer on the trip.
|
||||
await addReservationTraveler(t, flight.id, removed.id);
|
||||
expect(await repo.listTravelerIds(flight.id)).toEqual([user.id, friend.id].sort((a, b) => a - b));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* The forwarding addresses through their repository: a person's own address
|
||||
* and a trip's are told apart, renewing revokes instead of deleting so the old
|
||||
* token is still recognised, a mail notes the address it came in on, and the
|
||||
* people who hold a live address are named for the pause notice.
|
||||
*/
|
||||
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
|
||||
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let addresses: MailIngestAddressesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
addresses = t.repo(MailIngestAddresses);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const AT = dbNow(new Date('2026-11-01T10:00:00Z'));
|
||||
const LATER = dbNow(new Date('2026-11-02T10:00:00Z'));
|
||||
|
||||
describe('MailIngestAddressesRepository', () => {
|
||||
it('keeps a person’s own address apart from a trip’s', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const own = await addresses.insertAddress({
|
||||
userId: user.id,
|
||||
tripId: null,
|
||||
tokenHash: 'h-own',
|
||||
tokenEnc: 'e-own',
|
||||
createdAt: AT,
|
||||
});
|
||||
const forTrip = await addresses.insertAddress({
|
||||
userId: user.id,
|
||||
tripId: trip.id,
|
||||
tokenHash: 'h-trip',
|
||||
tokenEnc: 'e-trip',
|
||||
createdAt: AT,
|
||||
});
|
||||
|
||||
expect((await addresses.findLive(user.id, null))?.id).toBe(own);
|
||||
expect((await addresses.findLive(user.id, trip.id))?.id).toBe(forTrip);
|
||||
expect(await addresses.findById(forTrip)).toMatchObject({ trip_id: trip.id, token_enc: 'e-trip' });
|
||||
expect(await addresses.findById(forTrip + 100)).toBeNull();
|
||||
});
|
||||
|
||||
it('revokes the live address of one scope only, and still finds a revoked token', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const own = await addresses.insertAddress({
|
||||
userId: user.id,
|
||||
tripId: null,
|
||||
tokenHash: 'a',
|
||||
tokenEnc: 'x',
|
||||
createdAt: AT,
|
||||
});
|
||||
await addresses.insertAddress({ userId: user.id, tripId: trip.id, tokenHash: 'b', tokenEnc: 'y', createdAt: AT });
|
||||
|
||||
expect(await addresses.revokeLive(user.id, null, LATER)).toBe(1);
|
||||
expect(await addresses.findLive(user.id, null)).toBeNull();
|
||||
expect(await addresses.findLive(user.id, trip.id)).not.toBeNull();
|
||||
expect(await addresses.findByTokenHash('a')).toMatchObject({ id: own, revoked_at: LATER });
|
||||
expect(await addresses.findByTokenHash('none')).toBeNull();
|
||||
|
||||
expect(await addresses.revokeLive(user.id, trip.id, LATER)).toBe(1);
|
||||
expect(await addresses.findLive(user.id, trip.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('notes when a mail came in', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const id = await addresses.insertAddress({
|
||||
userId: user.id,
|
||||
tripId: null,
|
||||
tokenHash: 'c',
|
||||
tokenEnc: 'z',
|
||||
createdAt: AT,
|
||||
});
|
||||
await addresses.touchUsed(id, LATER);
|
||||
expect((await addresses.findById(id))?.last_used_at).toBe(LATER);
|
||||
});
|
||||
|
||||
it('names each person who holds an address that is not revoked, once', async () => {
|
||||
const { user: mia } = await makeUser(t);
|
||||
const { user: noah } = await makeUser(t);
|
||||
const trip = await makeTrip(t, mia.id);
|
||||
await addresses.insertAddress({ userId: mia.id, tripId: null, tokenHash: 'm1', tokenEnc: 'e', createdAt: AT });
|
||||
await addresses.insertAddress({ userId: mia.id, tripId: trip.id, tokenHash: 'm2', tokenEnc: 'e', createdAt: AT });
|
||||
await addresses.insertAddress({ userId: noah.id, tripId: null, tokenHash: 'n1', tokenEnc: 'e', createdAt: AT });
|
||||
expect(await addresses.listHolders()).toEqual([mia.id, noah.id].sort((a, b) => a - b));
|
||||
|
||||
await addresses.revokeLive(noah.id, null, LATER);
|
||||
expect(await addresses.listHolders()).toEqual([mia.id]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* The bookings read from mails through their repository, and what it reads
|
||||
* of the trips they may go to: a decision lands once, an undone booking is
|
||||
* remembered per trip, and only the person's open trips are weighed.
|
||||
*/
|
||||
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
|
||||
import { MailIngestCandidates } from '../../../../src/db/entities/MailIngestCandidates.entity';
|
||||
import { MailIngestMessages } from '../../../../src/db/entities/MailIngestMessages.entity';
|
||||
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
|
||||
import type {
|
||||
MailIngestCandidateInsert,
|
||||
MailIngestCandidatesRepository,
|
||||
} from '../../../../src/db/repositories/MailIngestCandidates.repository';
|
||||
import type { MailIngestMessagesRepository } from '../../../../src/db/repositories/MailIngestMessages.repository';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { addBudgetItemPayer, makeBudgetItem } from '../../../helpers/factories/budget';
|
||||
import { makeDayAssignment } from '../../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { makeReservation } from '../../../helpers/factories/reservations';
|
||||
import { addTripMember, makeTrip, readTripDays } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let candidates: MailIngestCandidatesRepository;
|
||||
let messages: MailIngestMessagesRepository;
|
||||
let addresses: MailIngestAddressesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
candidates = t.repo(MailIngestCandidates);
|
||||
messages = t.repo(MailIngestMessages);
|
||||
addresses = t.repo(MailIngestAddresses);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const at = (iso: string) => dbNow(new Date(iso));
|
||||
const DAY1 = at('2026-11-01T10:00:00Z');
|
||||
|
||||
async function mailOf(userId: number): Promise<number> {
|
||||
const addressId = await addresses.insertAddress({
|
||||
userId,
|
||||
tripId: null,
|
||||
tokenHash: `h${userId}`,
|
||||
tokenEnc: 'e',
|
||||
createdAt: DAY1,
|
||||
});
|
||||
const id = await messages.insertIfNew({
|
||||
transport: 'upload',
|
||||
messageIdHdr: null,
|
||||
dedupeHash: `d${userId}`,
|
||||
addressId,
|
||||
userId,
|
||||
tripId: null,
|
||||
size: 1,
|
||||
rawEnc: 'enc',
|
||||
receivedAt: DAY1,
|
||||
});
|
||||
if (id === null) throw new Error('the mail was stored already');
|
||||
return id;
|
||||
}
|
||||
|
||||
function entry(messageId: number, userId: number, over: Partial<MailIngestCandidateInsert> = {}) {
|
||||
return candidates.insertCandidate({
|
||||
messageId,
|
||||
userId,
|
||||
position: 0,
|
||||
itemJson: '{}',
|
||||
source: 'ai',
|
||||
checksJson: '{}',
|
||||
uncertainFields: '[]',
|
||||
matchJson: null,
|
||||
suggestedTripId: null,
|
||||
dedupeKey: null,
|
||||
contentHash: 'c1',
|
||||
resolution: 'pending',
|
||||
reason: 'trip_ambiguous',
|
||||
createdAt: DAY1,
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
describe('MailIngestCandidatesRepository: the entries', () => {
|
||||
it('lists a mail’s entries in order and counts the waiting ones', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const mail = await mailOf(user.id);
|
||||
const second = await entry(mail, user.id, { position: 1 });
|
||||
const first = await entry(mail, user.id, { position: 0, resolution: 'duplicate', reason: null });
|
||||
expect((await candidates.listForMessage(mail)).map((row) => row.id)).toEqual([first, second]);
|
||||
expect(await candidates.countPending(user.id)).toBe(1);
|
||||
expect(await candidates.findById(second)).toMatchObject({ source: 'ai', reason: 'trip_ambiguous' });
|
||||
expect(await candidates.findById(second + 10)).toBeNull();
|
||||
});
|
||||
|
||||
it('decides an entry once, and records its documents afterwards', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const mail = await mailOf(user.id);
|
||||
const id = await entry(mail, user.id);
|
||||
const patch = {
|
||||
resolution: 'applied',
|
||||
reason: null,
|
||||
resolvedTripId: trip.id,
|
||||
createdIdsJson: '{"reservation_ids":[1]}',
|
||||
resolvedBy: user.id,
|
||||
resolvedAt: DAY1,
|
||||
undoUntil: at('2026-11-08T10:00:00Z'),
|
||||
};
|
||||
expect(await candidates.resolve(id, ['pending'], patch)).toBe(true);
|
||||
expect(await candidates.resolve(id, ['pending'], patch)).toBe(false);
|
||||
|
||||
await candidates.setAttachments(id, '{"reservation_ids":[1],"file_ids":[2]}', null);
|
||||
expect(await candidates.findById(id)).toMatchObject({
|
||||
resolution: 'applied',
|
||||
resolved_trip_id: trip.id,
|
||||
created_ids_json: '{"reservation_ids":[1],"file_ids":[2]}',
|
||||
attach_error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('decides an added entry only while it still holds the trip and ids it was read with', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const other = await makeTrip(t, user.id);
|
||||
const mail = await mailOf(user.id);
|
||||
const id = await entry(mail, user.id);
|
||||
const added = {
|
||||
resolution: 'applied',
|
||||
reason: null,
|
||||
resolvedTripId: trip.id,
|
||||
createdIdsJson: '{"reservation_ids":[1]}',
|
||||
resolvedBy: user.id,
|
||||
resolvedAt: DAY1,
|
||||
undoUntil: at('2026-11-08T10:00:00Z'),
|
||||
};
|
||||
expect(await candidates.resolve(id, ['pending'], added)).toBe(true);
|
||||
const undone = { ...added, resolution: 'undone', undoUntil: null };
|
||||
|
||||
expect(
|
||||
await candidates.resolve(id, ['applied'], undone, { tripId: other.id, createdIdsJson: added.createdIdsJson }),
|
||||
).toBe(false);
|
||||
expect(await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: '{"x":1}' })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: null })).toBe(false);
|
||||
expect(await candidates.findById(id)).toMatchObject({ resolution: 'applied' });
|
||||
|
||||
expect(
|
||||
await candidates.resolve(id, ['applied'], undone, { tripId: trip.id, createdIdsJson: added.createdIdsJson }),
|
||||
).toBe(true);
|
||||
expect(await candidates.findById(id)).toMatchObject({ resolution: 'undone', resolved_trip_id: trip.id });
|
||||
});
|
||||
|
||||
it('writes an entry decided as it is written with its trip, ids and undo window', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const until = at('2026-11-08T10:00:00Z');
|
||||
const id = await entry(await mailOf(user.id), user.id, {
|
||||
resolution: 'auto_applied',
|
||||
reason: null,
|
||||
resolvedTripId: trip.id,
|
||||
createdIdsJson: '{"reservation_ids":[3]}',
|
||||
resolvedAt: DAY1,
|
||||
undoUntil: until,
|
||||
});
|
||||
expect(await candidates.findById(id)).toMatchObject({
|
||||
resolved_trip_id: trip.id,
|
||||
created_ids_json: '{"reservation_ids":[3]}',
|
||||
resolved_at: DAY1,
|
||||
undo_until: until,
|
||||
});
|
||||
});
|
||||
|
||||
it('remembers a booking undone in a trip by its content', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const id = await entry(await mailOf(user.id), user.id, { contentHash: 'same' });
|
||||
expect(await candidates.wasUndoneInTrip(trip.id, 'same')).toBe(false);
|
||||
await candidates.resolve(id, ['pending'], {
|
||||
resolution: 'undone',
|
||||
reason: null,
|
||||
resolvedTripId: trip.id,
|
||||
createdIdsJson: null,
|
||||
resolvedBy: user.id,
|
||||
resolvedAt: DAY1,
|
||||
undoUntil: null,
|
||||
});
|
||||
expect(await candidates.wasUndoneInTrip(trip.id, 'same')).toBe(true);
|
||||
expect(await candidates.wasUndoneInTrip(trip.id, 'other')).toBe(false);
|
||||
});
|
||||
|
||||
it('deletes decided entries past the cutoff and keeps the waiting ones', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const mail = await mailOf(user.id);
|
||||
const waiting = await entry(mail, user.id);
|
||||
const decided = await entry(mail, user.id, { position: 1 });
|
||||
await candidates.resolve(decided, ['pending'], {
|
||||
resolution: 'discarded',
|
||||
reason: null,
|
||||
resolvedTripId: null,
|
||||
createdIdsJson: null,
|
||||
resolvedBy: user.id,
|
||||
resolvedAt: at('2026-07-01T10:00:00Z'),
|
||||
undoUntil: null,
|
||||
});
|
||||
expect(await candidates.deleteResolvedBefore(at('2026-08-01T00:00:00Z'))).toBe(1);
|
||||
expect(await candidates.findById(waiting)).not.toBeNull();
|
||||
expect(await candidates.findById(decided)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MailIngestCandidatesRepository: what it reads of the trips', () => {
|
||||
it('lists the person’s open trips, owned or joined, newest start first', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: other } = await makeUser(t);
|
||||
const owned = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-03', currency: 'JPY' });
|
||||
const joined = await makeTrip(t, other.id, { start_date: '2027-05-01', end_date: '2027-05-02' });
|
||||
await addTripMember(t, joined.id, user.id);
|
||||
const undated = await makeTrip(t, user.id);
|
||||
await makeTrip(t, user.id, { start_date: '2026-01-01', end_date: '2026-01-02' });
|
||||
await makeTrip(t, user.id, { start_date: '2027-06-01', end_date: '2027-06-02', is_archived: 1 });
|
||||
await makeTrip(t, other.id, { start_date: '2027-07-01', end_date: '2027-07-02' });
|
||||
|
||||
const trips = await candidates.listOpenTrips(user.id, '2026-10-01', 20);
|
||||
expect(trips.map((trip) => trip.id).sort()).toEqual([owned.id, joined.id, undated.id].sort());
|
||||
expect(trips.find((trip) => trip.id === owned.id)).toMatchObject({ user_id: user.id, currency: 'JPY' });
|
||||
expect(await candidates.listOpenTrips(user.id, '2026-10-01', 1)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('finds one open trip of the person whatever its dates, and none of a stranger', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: other } = await makeUser(t);
|
||||
const ended = await makeTrip(t, user.id, { start_date: '2025-01-01', end_date: '2025-01-02' });
|
||||
const archived = await makeTrip(t, user.id, { is_archived: 1 });
|
||||
const foreign = await makeTrip(t, other.id);
|
||||
expect(await candidates.findOpenTrip(user.id, ended.id)).toMatchObject({ id: ended.id, user_id: user.id });
|
||||
expect(await candidates.findOpenTrip(user.id, archived.id)).toBeNull();
|
||||
expect(await candidates.findOpenTrip(user.id, foreign.id)).toBeNull();
|
||||
await addTripMember(t, foreign.id, user.id);
|
||||
expect(await candidates.findOpenTrip(user.id, foreign.id)).toMatchObject({ id: foreign.id });
|
||||
});
|
||||
|
||||
it('reads the dated days and the placed places of trips', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-02' });
|
||||
await makePlace(t, trip.id, { name: 'Hotel Sakura', address: 'Tokyo', lat: 35.68, lng: 139.76 });
|
||||
await makePlace(t, trip.id, { name: 'Somewhere', lat: null, lng: null });
|
||||
|
||||
const days = await candidates.listDatedDays([trip.id]);
|
||||
expect(days.map(({ trip_id, date }) => [trip_id, date])).toEqual([
|
||||
[trip.id, '2027-03-01'],
|
||||
[trip.id, '2027-03-02'],
|
||||
]);
|
||||
expect(days.every((day) => day.id > 0)).toBe(true);
|
||||
expect(await candidates.listDatedDays([])).toEqual([]);
|
||||
expect(await candidates.listPlacesWithPosition([trip.id])).toEqual([
|
||||
{ trip_id: trip.id, name: 'Hotel Sakura', address: 'Tokyo', lat: 35.68, lng: 139.76 },
|
||||
]);
|
||||
expect(await candidates.listPlacesWithPosition([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads the person a mail is for', async () => {
|
||||
const { user } = await makeUser(t, { username: 'mia', email: 'mia@example.com' });
|
||||
expect(await candidates.findPerson(user.id)).toEqual({
|
||||
id: user.id,
|
||||
username: 'mia',
|
||||
email: 'mia@example.com',
|
||||
role: 'user',
|
||||
});
|
||||
expect(await candidates.findPerson(user.id + 100)).toBeNull();
|
||||
});
|
||||
|
||||
it('finds a booking an import stored under a key, and one that looks the same', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
await makeReservation(t, trip.id, {
|
||||
type: 'flight',
|
||||
reservation_time: '2027-03-01T10:00',
|
||||
confirmation_number: 'ABC123',
|
||||
external_source: 'mail',
|
||||
external_id: 'ABC123|flight|2027-03-01|hnd-itm',
|
||||
});
|
||||
|
||||
const key = 'ABC123|flight|2027-03-01|hnd-itm';
|
||||
expect(await candidates.tripHasExternal(trip.id, ['import', 'mail'], key)).toBe(true);
|
||||
expect(await candidates.tripHasExternal(trip.id, ['import'], key)).toBe(false);
|
||||
|
||||
const none = { type: 'flight', startFrom: null, startTo: null, confirmation: null };
|
||||
expect(await candidates.tripHasSimilar(trip.id, none)).toBe(false);
|
||||
expect(await candidates.tripHasSimilar(trip.id, { ...none, confirmation: 'ABC123' })).toBe(true);
|
||||
expect(
|
||||
await candidates.tripHasSimilar(trip.id, { ...none, startFrom: '2027-03-01T09:30', startTo: '2027-03-01T10:30' }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
await candidates.tripHasSimilar(trip.id, {
|
||||
...none,
|
||||
type: 'train',
|
||||
startFrom: '2027-03-01T09:30',
|
||||
startTo: '2027-03-01T10:30',
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('tells a place something still names from one nothing does', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id, { start_date: '2027-03-01', end_date: '2027-03-01' });
|
||||
const [day] = await readTripDays(t, trip.id);
|
||||
const free = await makePlace(t, trip.id);
|
||||
const booked = await makePlace(t, trip.id);
|
||||
const planned = await makePlace(t, trip.id);
|
||||
await makeReservation(t, trip.id, { place: booked.id });
|
||||
await makeDayAssignment(t, day.id, planned.id);
|
||||
expect(await candidates.placeInUse(free.id)).toBe(false);
|
||||
expect(await candidates.placeInUse(booked.id)).toBe(true);
|
||||
expect(await candidates.placeInUse(planned.id)).toBe(true);
|
||||
});
|
||||
|
||||
it('counts the payers of costs', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const paid = await makeBudgetItem(t, trip.id);
|
||||
const open = await makeBudgetItem(t, trip.id);
|
||||
await addBudgetItemPayer(t, paid.id, user.id, 100);
|
||||
expect(await candidates.countPayers([paid.id, open.id])).toBe(1);
|
||||
expect(await candidates.countPayers([open.id])).toBe(0);
|
||||
expect(await candidates.countPayers([])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MailIngestCandidatesRepository: the inbox and its counts', () => {
|
||||
it('pages a person’s open or decided entries, newest first', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: other } = await makeUser(t);
|
||||
const mail = await mailOf(user.id);
|
||||
const oldest = await entry(mail, user.id);
|
||||
const middle = await entry(mail, user.id, { position: 1 });
|
||||
const newest = await entry(mail, user.id, { position: 2 });
|
||||
const decided = await entry(mail, user.id, { position: 3, resolution: 'discarded', reason: null });
|
||||
await entry(await mailOf(other.id), other.id);
|
||||
|
||||
const open = await candidates.listForUser(user.id, true, null, 2);
|
||||
expect(open.map((row) => row.id)).toEqual([newest, middle]);
|
||||
expect((await candidates.listForUser(user.id, true, middle, 10)).map((row) => row.id)).toEqual([oldest]);
|
||||
expect((await candidates.listForUser(user.id, false, null, 10)).map((row) => row.id)).toEqual([decided]);
|
||||
});
|
||||
|
||||
it('names only the trips the reader owns or joined', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: other } = await makeUser(t);
|
||||
const owned = await makeTrip(t, user.id, { title: 'Japan', start_date: '2027-03-01', end_date: '2027-03-03' });
|
||||
const joined = await makeTrip(t, other.id, { title: 'Lisbon' });
|
||||
await addTripMember(t, joined.id, user.id);
|
||||
const foreign = await makeTrip(t, other.id, { title: 'Secret' });
|
||||
|
||||
const refs = await candidates.listTripRefs(user.id, [owned.id, joined.id, foreign.id]);
|
||||
expect(refs.sort((a, b) => a.id - b.id)).toEqual([
|
||||
{ id: owned.id, title: 'Japan', start_date: '2027-03-01', end_date: '2027-03-03' },
|
||||
{ id: joined.id, title: 'Lisbon', start_date: null, end_date: null },
|
||||
]);
|
||||
expect(await candidates.listTripRefs(user.id, [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('counts the entries made since a time by outcome, and the waiting ones per person', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const { user: other } = await makeUser(t);
|
||||
const mail = await mailOf(user.id);
|
||||
await entry(mail, user.id);
|
||||
await entry(mail, user.id, { position: 1 });
|
||||
await entry(mail, user.id, { position: 2, resolution: 'auto_applied', reason: null });
|
||||
await entry(mail, user.id, { position: 3, resolution: 'undone', createdAt: at('2026-10-01T10:00:00Z') });
|
||||
await entry(await mailOf(other.id), other.id);
|
||||
|
||||
const tally = await candidates.tallyResolutionsSince(at('2026-10-15T00:00:00Z'));
|
||||
expect(tally.sort((a, b) => a.resolution.localeCompare(b.resolution))).toEqual([
|
||||
{ resolution: 'auto_applied', n: 1 },
|
||||
{ resolution: 'pending', n: 3 },
|
||||
]);
|
||||
expect(await candidates.pendingPerUser()).toEqual([2, 1]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* The readers' cursor: one holder of a lease at a time, a lease that ran out
|
||||
* is taken over, and a run's position and error are kept for the admin.
|
||||
*/
|
||||
import { MailIngestCursor } from '../../../../src/db/entities/MailIngestCursor.entity';
|
||||
import type { MailIngestCursorRepository } from '../../../../src/db/repositories/MailIngestCursor.repository';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let cursor: MailIngestCursorRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
cursor = t.repo(MailIngestCursor);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const T0 = dbNow(new Date('2026-11-01T10:00:00Z'));
|
||||
const T1 = dbNow(new Date('2026-11-01T10:05:00Z'));
|
||||
const T2 = dbNow(new Date('2026-11-01T10:10:00Z'));
|
||||
|
||||
describe('MailIngestCursorRepository', () => {
|
||||
it('gives the lease to one owner until it runs out or is given back', async () => {
|
||||
expect(await cursor.acquireLease('pipeline', '', 'a', T1, T0)).toBe(true);
|
||||
expect(await cursor.acquireLease('pipeline', '', 'b', T1, T0)).toBe(false);
|
||||
// The holder renews its own lease.
|
||||
expect(await cursor.acquireLease('pipeline', '', 'a', T2, T0)).toBe(true);
|
||||
// Run out: another takes it.
|
||||
expect(await cursor.acquireLease('pipeline', '', 'b', T2, dbNow(new Date('2026-11-01T10:11:00Z')))).toBe(true);
|
||||
|
||||
await cursor.releaseLease('pipeline', '', 'a');
|
||||
expect(await cursor.findCursor('pipeline', '')).toMatchObject({ lease_owner: 'b' });
|
||||
await cursor.releaseLease('pipeline', '', 'b');
|
||||
expect(await cursor.findCursor('pipeline', '')).toMatchObject({ lease_owner: null, lease_until: null });
|
||||
});
|
||||
|
||||
it('keeps the position of a good run and the error of a bad one', async () => {
|
||||
await cursor.acquireLease('imap', 'INBOX', 'a', T1, T0);
|
||||
await cursor.recordOk('imap', 'INBOX', T0, { uidValidity: 7, lastUid: 42 });
|
||||
await cursor.recordError('imap', 'INBOX', 'x'.repeat(600));
|
||||
let row = await cursor.findCursor('imap', 'INBOX');
|
||||
expect(row).toMatchObject({ uid_validity: 7, last_uid: 42, last_ok_at: T0 });
|
||||
expect(row?.last_error).toHaveLength(500);
|
||||
|
||||
await cursor.recordOk('imap', 'INBOX', T1);
|
||||
row = await cursor.findCursor('imap', 'INBOX');
|
||||
expect(row).toMatchObject({ uid_validity: 7, last_uid: 42, last_ok_at: T1, last_error: null });
|
||||
|
||||
await cursor.forgetOk('imap', 'INBOX');
|
||||
expect(await cursor.findCursor('imap', 'INBOX')).toMatchObject({ uid_validity: 7, last_ok_at: null });
|
||||
expect(await cursor.findCursor('cloud', '')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the pause notice as a reader of its own, as the schema allows', async () => {
|
||||
// The pause job takes this lease before it tells anyone; the insert behind
|
||||
// it once failed the transport CHECK, so nobody was ever told.
|
||||
expect(await cursor.acquireLease('notice', 'paused', 'a', T1, T0)).toBe(true);
|
||||
await cursor.recordOk('notice', 'paused', T0);
|
||||
expect(await cursor.findCursor('notice', 'paused')).toMatchObject({ last_ok_at: T0, lease_owner: 'a' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Forwarded mails through their repository: a mail delivered twice is stored
|
||||
* once, a due mail is claimed by one run, a run whose claim ran out hands the
|
||||
* mail on, and the retention keeps a mail while its inbox entry waits.
|
||||
*/
|
||||
import { MailIngestAddresses } from '../../../../src/db/entities/MailIngestAddresses.entity';
|
||||
import { MailIngestCandidates } from '../../../../src/db/entities/MailIngestCandidates.entity';
|
||||
import { MailIngestMessages } from '../../../../src/db/entities/MailIngestMessages.entity';
|
||||
import type { MailIngestAddressesRepository } from '../../../../src/db/repositories/MailIngestAddresses.repository';
|
||||
import type { MailIngestCandidatesRepository } from '../../../../src/db/repositories/MailIngestCandidates.repository';
|
||||
import type {
|
||||
MailIngestMessageOutcome,
|
||||
MailIngestMessagesRepository,
|
||||
} from '../../../../src/db/repositories/MailIngestMessages.repository';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let messages: MailIngestMessagesRepository;
|
||||
let addresses: MailIngestAddressesRepository;
|
||||
let candidates: MailIngestCandidatesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
messages = t.repo(MailIngestMessages);
|
||||
addresses = t.repo(MailIngestAddresses);
|
||||
candidates = t.repo(MailIngestCandidates);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const at = (iso: string) => dbNow(new Date(iso));
|
||||
const DAY1 = at('2026-11-01T10:00:00Z');
|
||||
|
||||
async function inbox() {
|
||||
const { user } = await makeUser(t);
|
||||
const addressId = await addresses.insertAddress({
|
||||
userId: user.id,
|
||||
tripId: null,
|
||||
tokenHash: `h${user.id}`,
|
||||
tokenEnc: 'e',
|
||||
createdAt: DAY1,
|
||||
});
|
||||
return { userId: user.id, addressId };
|
||||
}
|
||||
|
||||
/** Stores a mail and answers its id; a second store of the same hash fails the test. */
|
||||
async function store(box: { userId: number; addressId: number }, hash: string, receivedAt = DAY1): Promise<number> {
|
||||
const id = await insert(box, hash, receivedAt);
|
||||
if (id === null) throw new Error(`mail ${hash} was stored already`);
|
||||
return id;
|
||||
}
|
||||
|
||||
function insert(box: { userId: number; addressId: number }, hash: string, receivedAt = DAY1) {
|
||||
return messages.insertIfNew({
|
||||
transport: 'upload',
|
||||
messageIdHdr: `<${hash}@x>`,
|
||||
dedupeHash: hash,
|
||||
addressId: box.addressId,
|
||||
userId: box.userId,
|
||||
tripId: null,
|
||||
size: 10,
|
||||
rawEnc: 'enc',
|
||||
receivedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const DONE: MailIngestMessageOutcome = {
|
||||
status: 'processed',
|
||||
reason: null,
|
||||
subject: 'Booking',
|
||||
fromAddr: 'a@b.c',
|
||||
fromVerified: true,
|
||||
authResults: 'dkim=pass',
|
||||
hints: '[]',
|
||||
attachments: '[]',
|
||||
forwardingCode: null,
|
||||
aiUsed: true,
|
||||
processedAt: DAY1,
|
||||
};
|
||||
|
||||
describe('MailIngestMessagesRepository', () => {
|
||||
it('stores a mail once and finds it by its hash', async () => {
|
||||
const box = await inbox();
|
||||
const id = await store(box, 'm1');
|
||||
expect(await insert(box, 'm1')).toBeNull();
|
||||
expect(await messages.findIdByDedupeHash('m1')).toBe(id);
|
||||
expect(await messages.findIdByDedupeHash('m2')).toBeNull();
|
||||
expect(await messages.findById(id)).toMatchObject({ status: 'queued', attempts: 0, raw_eml_enc: 'enc' });
|
||||
expect(await messages.findById(id + 1)).toBeNull();
|
||||
});
|
||||
|
||||
it('counts the mails of an address and the AI-read mails of a person since a time', async () => {
|
||||
const box = await inbox();
|
||||
const first = await store(box, 'c1', at('2026-10-31T10:00:00Z'));
|
||||
await store(box, 'c2', DAY1);
|
||||
expect(await messages.countForAddressSince(box.addressId, at('2026-11-01T00:00:00Z'))).toBe(1);
|
||||
await messages.finish(first, DONE);
|
||||
expect(await messages.countAiReadSince(box.userId, at('2026-10-31T00:00:00Z'))).toBe(1);
|
||||
expect(await messages.countAiReadSince(box.userId, at('2026-11-01T00:00:00Z'))).toBe(0);
|
||||
});
|
||||
|
||||
it('lists mails without their content, and counts everyone’s by status, reason and AI', async () => {
|
||||
const box = await inbox();
|
||||
const read = await store(box, 'h1');
|
||||
const dropped = await store(box, 'h2');
|
||||
await store(box, 'h3', at('2026-10-01T10:00:00Z'));
|
||||
await messages.finish(read, DONE);
|
||||
await messages.finish(dropped, { ...DONE, status: 'discarded', reason: 'newsletter', aiUsed: false });
|
||||
|
||||
const heads = await messages.listHeads([read, dropped]);
|
||||
expect(heads.map((head) => head.id).sort()).toEqual([read, dropped].sort());
|
||||
expect(heads[0]).not.toHaveProperty('raw_eml_enc');
|
||||
expect(heads[0]).not.toHaveProperty('auth_results');
|
||||
expect(await messages.listHeads([])).toEqual([]);
|
||||
|
||||
const tally = await messages.tallySince(at('2026-10-15T00:00:00Z'));
|
||||
expect(tally.sort((a, b) => a.status.localeCompare(b.status))).toEqual([
|
||||
{ status: 'discarded', reason: 'newsletter', n: 1 },
|
||||
{ status: 'processed', reason: null, n: 1 },
|
||||
]);
|
||||
expect(await messages.countAllAiReadSince(at('2026-10-15T00:00:00Z'))).toBe(1);
|
||||
});
|
||||
|
||||
it('claims a due mail for one run and lets a claim that ran out go to the next', async () => {
|
||||
const box = await inbox();
|
||||
const id = await store(box, 'd1');
|
||||
await store(box, 'd2', at('2026-11-05T10:00:00Z'));
|
||||
|
||||
const now = at('2026-11-01T11:00:00Z');
|
||||
const lease = at('2026-11-01T11:10:00Z');
|
||||
expect(await messages.claimDue(now, lease, 3)).toEqual([id]);
|
||||
expect(await messages.claimDue(now, lease, 3)).toEqual([]);
|
||||
|
||||
const later = at('2026-11-01T11:20:00Z');
|
||||
expect(await messages.claimDue(later, at('2026-11-01T11:30:00Z'), 3)).toEqual([id]);
|
||||
expect(await messages.findById(id)).toMatchObject({ status: 'processing', attempts: 2 });
|
||||
|
||||
await messages.retryLater(id, at('2026-11-01T12:00:00Z'));
|
||||
expect(await messages.claimDue(later, lease, 3)).toEqual([]);
|
||||
expect(await messages.claimDue(at('2026-11-01T12:00:00Z'), lease, 3)).toEqual([id]);
|
||||
|
||||
await messages.finish(id, DONE);
|
||||
expect(await messages.findById(id)).toMatchObject({
|
||||
status: 'processed',
|
||||
ai_used: 1,
|
||||
from_verified: 1,
|
||||
lease_until: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('purges a mail once it is done and nothing waits on it, and always after the hard limit', async () => {
|
||||
const box = await inbox();
|
||||
const waiting = await store(box, 'p1');
|
||||
const settled = await store(box, 'p2');
|
||||
const old = await store(box, 'p3', at('2026-09-01T10:00:00Z'));
|
||||
await messages.finish(waiting, DONE);
|
||||
await messages.finish(settled, DONE);
|
||||
await candidates.insertCandidate({
|
||||
messageId: waiting,
|
||||
userId: box.userId,
|
||||
position: 0,
|
||||
itemJson: null,
|
||||
source: null,
|
||||
checksJson: null,
|
||||
uncertainFields: null,
|
||||
matchJson: null,
|
||||
suggestedTripId: null,
|
||||
dedupeKey: null,
|
||||
contentHash: null,
|
||||
resolution: 'pending',
|
||||
reason: 'no_trip_in_range',
|
||||
createdAt: DAY1,
|
||||
});
|
||||
|
||||
const purgedAt = at('2026-11-20T10:00:00Z');
|
||||
expect(await messages.purgeRaw(at('2026-11-10T10:00:00Z'), at('2026-10-01T10:00:00Z'), purgedAt)).toBe(2);
|
||||
expect(await messages.findById(waiting)).toMatchObject({ raw_eml_enc: 'enc', raw_purged_at: null });
|
||||
expect(await messages.findById(settled)).toMatchObject({ raw_eml_enc: null, raw_purged_at: purgedAt });
|
||||
expect(await messages.findById(old)).toMatchObject({ raw_eml_enc: null });
|
||||
});
|
||||
|
||||
it('deletes settled mails without entries, and keeps queued ones and those with entries', async () => {
|
||||
const box = await inbox();
|
||||
const queued = await store(box, 'x1', at('2026-08-01T10:00:00Z'));
|
||||
const bare = await store(box, 'x2', at('2026-08-01T10:00:00Z'));
|
||||
const withEntry = await store(box, 'x3', at('2026-08-01T10:00:00Z'));
|
||||
await messages.finish(bare, { ...DONE, status: 'discarded' });
|
||||
await messages.finish(withEntry, DONE);
|
||||
await candidates.insertCandidate({
|
||||
messageId: withEntry,
|
||||
userId: box.userId,
|
||||
position: 0,
|
||||
itemJson: null,
|
||||
source: null,
|
||||
checksJson: null,
|
||||
uncertainFields: null,
|
||||
matchJson: null,
|
||||
suggestedTripId: null,
|
||||
dedupeKey: null,
|
||||
contentHash: null,
|
||||
resolution: 'discarded',
|
||||
reason: null,
|
||||
createdAt: DAY1,
|
||||
});
|
||||
|
||||
expect(await messages.deleteSettledBefore(at('2026-09-01T00:00:00Z'))).toBe(1);
|
||||
expect(await messages.findById(bare)).toBeNull();
|
||||
expect(await messages.findById(queued)).not.toBeNull();
|
||||
expect(await messages.findById(withEntry)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* A person's switches for the mail import: no row until something changes,
|
||||
* and a write names only the switches it changes.
|
||||
*/
|
||||
import { MailIngestPrefs } from '../../../../src/db/entities/MailIngestPrefs.entity';
|
||||
import type { MailIngestPrefsRepository } from '../../../../src/db/repositories/MailIngestPrefs.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let prefs: MailIngestPrefsRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
prefs = t.repo(MailIngestPrefs);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('MailIngestPrefsRepository', () => {
|
||||
it('has no row until a switch changes, then the defaults for the others', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
expect(await prefs.findForUser(user.id)).toBeNull();
|
||||
|
||||
await prefs.upsertForUser(user.id, { auto_add: 0 });
|
||||
expect(await prefs.findForUser(user.id)).toMatchObject({ enabled: 1, ai_enabled: 1, auto_add: 0 });
|
||||
|
||||
await prefs.upsertForUser(user.id, { ai_enabled: 0 });
|
||||
expect(await prefs.findForUser(user.id)).toMatchObject({ enabled: 1, ai_enabled: 0, auto_add: 0 });
|
||||
});
|
||||
|
||||
it('writes nothing for an empty change', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
await prefs.upsertForUser(user.id, {});
|
||||
expect(await prefs.findForUser(user.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -112,3 +112,22 @@ describe('PackingItemsRepository — share.service.ts SH13 read', () => {
|
||||
expect(await packingItemsRepo.listPublicForShare(trip.id)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PackingItemsRepository — clearOwner (#3098)', () => {
|
||||
it('drops the owner of one item, keeps its tier and leaves the other items alone', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
const item = createPackingItem(testDb, trip.id, { name: 'Stove' });
|
||||
const other = createPackingItem(testDb, trip.id, { name: 'Pot' });
|
||||
await updateRows(t, PackingItems, { id: item.id }, { is_private: 0, owner: owner.id, updated_at: null });
|
||||
await updateRows(t, PackingItems, { id: other.id }, { is_private: 0, owner: owner.id });
|
||||
|
||||
await packingItemsRepo.clearOwner(item.id);
|
||||
|
||||
const row = await packingItemsRepo.findById(item.id);
|
||||
expect(row?.owner_id).toBeNull();
|
||||
expect(row?.is_private).toBe(0);
|
||||
expect(row?.updated_at).not.toBeNull();
|
||||
expect((await packingItemsRepo.findById(other.id))?.owner_id).toBe(owner.id);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -166,11 +166,26 @@ describe('PlaceRegionsRepository.listStartedTripPlaceCountriesForUser (AT44)', (
|
||||
|
||||
const today = '2026-01-01';
|
||||
const expected = [
|
||||
{ id: cached.id, lat: 48.85, lng: 2.35, address: null, country_code: 'FR' },
|
||||
{ id: uncached.id, lat: 41.9022, lng: 12.4539, address: null, country_code: null },
|
||||
{ id: cached.id, lat: 48.85, lng: 2.35, address: null, country_code: 'FR', trip_last_date: '2020-01-10' },
|
||||
{ id: uncached.id, lat: 41.9022, lng: 12.4539, address: null, country_code: null, trip_last_date: '2020-01-10' },
|
||||
];
|
||||
expect(await repo.listStartedTripPlaceCountriesForUser(owner.id, today)).toEqual(expected);
|
||||
expect(await repo.listStartedTripPlaceCountriesForUser(member.id, today)).toEqual(expected);
|
||||
expect(await repo.listStartedTripPlaceCountriesForUser(stranger.id, today)).toEqual([]);
|
||||
});
|
||||
|
||||
it('PLACEREGREPO-010: dates each place by its own trip, the start standing in for a missing end (#2648)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const ended = createTrip(testDb, user.id, { start_date: '2020-01-01', end_date: '2020-01-10' });
|
||||
const openEnded = createTrip(testDb, user.id, { start_date: '2021-07-01' });
|
||||
const first = createPlace(testDb, ended.id);
|
||||
const second = createPlace(testDb, openEnded.id);
|
||||
|
||||
const rows = await repo.listStartedTripPlaceCountriesForUser(user.id, '2026-01-01');
|
||||
|
||||
expect(rows.map((row) => [row.id, row.trip_last_date])).toEqual([
|
||||
[first.id, '2020-01-10'],
|
||||
[second.id, '2021-07-01'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -525,7 +525,8 @@ describe('ReservationsRepository — AC37/AC40 (listIdMetadataByStay/listIdsBySt
|
||||
describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins / findInTrip / listResyncCandidates / listForRestamp)', () => {
|
||||
const legacyJoinedSql = `
|
||||
SELECT r.*, d.day_number as day_number, p.name as place_name, ap.place_id as accommodation_place_id,
|
||||
acc_p.name as accommodation_name, ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id
|
||||
acc_p.name as accommodation_name, ap.start_day_id as accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id,
|
||||
ap.check_in as accommodation_check_in, ap.check_in_end as accommodation_check_in_end, ap.check_out as accommodation_check_out
|
||||
FROM reservations r
|
||||
LEFT JOIN days d ON d.id = r.day_id
|
||||
LEFT JOIN places p ON p.id = r.place_id
|
||||
@@ -562,10 +563,10 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
|
||||
});
|
||||
|
||||
it('RR1 findWithJoins — matches the legacy joined statement for one row, place/accommodation columns populated', async () => {
|
||||
const { hotel, stay, hotelPlace } = await seed();
|
||||
const { trip, hotel, stay, hotelPlace } = await seed();
|
||||
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
|
||||
const legacy = testDb.prepare(`${legacyJoinedSql} WHERE r.id = ?`).get(hotel.id);
|
||||
const typed = await reservationsRepo.findWithJoins(hotel.id);
|
||||
const typed = await reservationsRepo.findWithJoins(hotel.id, trip.id);
|
||||
expect(typed).toEqual(legacy);
|
||||
expect(typed).toMatchObject({
|
||||
accommodation_place_id: hotelPlace.id,
|
||||
@@ -574,6 +575,14 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
|
||||
});
|
||||
});
|
||||
|
||||
it('RR1 findWithJoins — a booking of another trip reads as missing', async () => {
|
||||
const { trip, hotel } = await seed();
|
||||
const { user } = createUser(testDb);
|
||||
const other = createTrip(testDb, user.id);
|
||||
expect(await reservationsRepo.findWithJoins(hotel.id, other.id)).toBeUndefined();
|
||||
expect(await reservationsRepo.findWithJoins(hotel.id, String(trip.id))).toMatchObject({ id: hotel.id });
|
||||
});
|
||||
|
||||
it('RS35 findInTrip — matches the legacy statement, scoped by trip', async () => {
|
||||
const { trip, dinner } = await seed();
|
||||
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
|
||||
@@ -1032,3 +1041,102 @@ describe('ReservationsRepository — confirmIfPending', () => {
|
||||
expect((await findRow(await orm(), Reservations, { id: cancelled.id }))?.status).toBe('cancelled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReservationsRepository — findPassContext', () => {
|
||||
it('RES-PASS-001: reads the trip title and the place of the booking, else of its stay, within the trip only', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { title: 'Japan 2027', start_date: '2027-04-01', end_date: '2027-04-06' });
|
||||
const day1 = createDay(testDb, trip.id, { date: '2027-04-01' });
|
||||
const day2 = createDay(testDb, trip.id, { date: '2027-04-02' });
|
||||
const restaurant = createPlace(testDb, trip.id, { name: 'Gion Karyo', lat: 35.0, lng: 135.77 });
|
||||
const hotel = createPlace(testDb, trip.id, { name: 'Hotel Granvia Kyoto', lat: 34.985, lng: 135.758 });
|
||||
const stay = createDayAccommodation(testDb, trip.id, hotel.id, day1.id, day2.id);
|
||||
|
||||
const dinner = createReservation(testDb, trip.id, { title: 'Dinner', type: 'restaurant' });
|
||||
await setReservation(dinner.id, { place: restaurant.id });
|
||||
const room = createReservation(testDb, trip.id, { title: 'Room', type: 'hotel' });
|
||||
await setReservation(room.id, { accommodation_id: String(stay.id) });
|
||||
const bare = createReservation(testDb, trip.id, { title: 'Museum', type: 'event' });
|
||||
|
||||
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toEqual({
|
||||
trip_title: 'Japan 2027',
|
||||
place_lat: 35.0,
|
||||
place_lng: 135.77,
|
||||
place_name: 'Gion Karyo',
|
||||
});
|
||||
expect(await reservationsRepo.findPassContext(room.id, trip.id)).toMatchObject({
|
||||
place_lat: 34.985,
|
||||
place_name: 'Hotel Granvia Kyoto',
|
||||
});
|
||||
expect(await reservationsRepo.findPassContext(bare.id, trip.id)).toEqual({
|
||||
trip_title: 'Japan 2027',
|
||||
place_lat: null,
|
||||
place_lng: null,
|
||||
place_name: null,
|
||||
});
|
||||
const other = createTrip(testDb, user.id, { title: 'Elsewhere' });
|
||||
expect(await reservationsRepo.findPassContext(dinner.id, other.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReservationsRepository — the origin of an imported booking', () => {
|
||||
const baseRow = (tripId: number) => ({
|
||||
trip_id: tripId,
|
||||
day_id: null,
|
||||
end_day_id: null,
|
||||
place_id: null,
|
||||
assignment_id: null,
|
||||
title: 'LH 716',
|
||||
reservation_time: null,
|
||||
reservation_end_time: null,
|
||||
location: null,
|
||||
confirmation_number: 'ABC123',
|
||||
notes: null,
|
||||
url: null,
|
||||
status: 'pending',
|
||||
type: 'flight',
|
||||
accommodation_id: null,
|
||||
metadata: null,
|
||||
needs_review: 0,
|
||||
});
|
||||
|
||||
it('RES-ORIGIN-001: a hand-made booking keeps the column defaults, no origin and sync on', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const id = await reservationsRepo.insertReservation(baseRow(trip.id));
|
||||
// test-sql-allow: reads back the raw columns the insert left to their defaults.
|
||||
const row = testDb
|
||||
.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?')
|
||||
.get(id);
|
||||
expect(row).toEqual({ external_source: null, external_id: null, sync_enabled: 1 });
|
||||
});
|
||||
|
||||
it('RES-ORIGIN-002: an imported booking records its origin and is found by it in its own trip only', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const id = await reservationsRepo.insertReservation({
|
||||
...baseRow(trip.id),
|
||||
external_source: 'import',
|
||||
external_id: 'ABC123|flight|2026-09-01|FRA-NRT',
|
||||
sync_enabled: 0,
|
||||
});
|
||||
// test-sql-allow: reads back the raw origin columns the insert named.
|
||||
const row = testDb
|
||||
.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?')
|
||||
.get(id);
|
||||
expect(row).toEqual({
|
||||
external_source: 'import',
|
||||
external_id: 'ABC123|flight|2026-09-01|FRA-NRT',
|
||||
sync_enabled: 0,
|
||||
});
|
||||
|
||||
expect(await reservationsRepo.findIdByExternal(trip.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT')).toBe(id);
|
||||
expect(
|
||||
await reservationsRepo.findIdByExternal(other.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT'),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
await reservationsRepo.findIdByExternal(trip.id, 'mail', 'ABC123|flight|2026-09-01|FRA-NRT'),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { withRequestContext } from '../../../../src/nest/database/request-contex
|
||||
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { createPlace, createTag, createTrip, createUser } from '../../../helpers/factories';
|
||||
import { tagPlace } from '../../../helpers/factories/places';
|
||||
import { makeTag, tagPlace } from '../../../helpers/factories/places';
|
||||
import { findRows } from '../../../helpers/factories/rows';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
@@ -380,7 +380,76 @@ describe('TagsRepository', () => {
|
||||
// Plan 3c Task 4 — findByIds (PL2) and the place_tags pivot writes (PL5/PL12/PL13).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TagsRepository: the tags a trip owns', () => {
|
||||
it('TRIPTAGREPO-001: listByTrip returns the rows of that trip by name, whoever created them, as SELECT * rows', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb, { username: 'trip_member' });
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
const other = createTrip(testDb, owner.id);
|
||||
const zone = await makeTag(t, owner.id, { trip: trip.id, name: 'Zone' });
|
||||
const activity = await makeTag(t, member.id, { trip: trip.id, name: 'Activity' });
|
||||
await makeTag(t, owner.id, { trip: other.id, name: 'Elsewhere' });
|
||||
createTag(testDb, owner.id, { name: 'personal' });
|
||||
|
||||
const rows = await tags.listByTrip(trip.id);
|
||||
|
||||
expect(rows).toStrictEqual([rawTag(activity.id), rawTag(zone.id)]);
|
||||
expect(rows.map((row) => row.trip_id)).toEqual([trip.id, trip.id]);
|
||||
expect(await tags.listByTrip(999999)).toEqual([]);
|
||||
});
|
||||
|
||||
it('TRIPTAGREPO-002: findByIdAndTrip finds a tag of that trip, and neither a personal tag nor another trip’s', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' });
|
||||
const ofOther = await makeTag(t, user.id, { trip: other.id, name: 'Elsewhere' });
|
||||
const personal = createTag(testDb, user.id, { name: 'personal' });
|
||||
|
||||
expect(await tags.findByIdAndTrip(ofTrip.id, trip.id)).toStrictEqual(rawTag(ofTrip.id));
|
||||
expect(await tags.findByIdAndTrip(ofOther.id, trip.id)).toBeNull();
|
||||
expect(await tags.findByIdAndTrip(personal.id, trip.id)).toBeNull();
|
||||
expect(await tags.findByIdAndTrip(999999, trip.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('TRIPTAGREPO-003: createTag files the row under the trip it is given, and under none when it is given none', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
const ofTrip = await tags.createTag({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' });
|
||||
const personal = await tags.createTag({ user_id: user.id, name: 'Monument', color: null });
|
||||
|
||||
expect(ofTrip).toStrictEqual(rawTag(ofTrip.id));
|
||||
expect(ofTrip).toMatchObject({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' });
|
||||
expect(personal).toMatchObject({ user_id: user.id, trip_id: null, color: null });
|
||||
});
|
||||
|
||||
it('TRIPTAGREPO-004: a personal tag still reads through listByUser and findByIdAndUser with a null trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const personal = createTag(testDb, user.id, { name: 'personal' });
|
||||
|
||||
expect((await tags.listByUser(user.id)).map((row) => row.trip_id)).toEqual([null]);
|
||||
expect((await tags.findByIdAndUser(personal.id, user.id))?.trip_id).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TagsRepository.findByIds (PL2)', () => {
|
||||
it('FINDBYIDSREPO-002: says which trip each tag belongs to, null for a personal one', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' });
|
||||
const personal = createTag(testDb, user.id, { name: 'personal' });
|
||||
|
||||
const rows = await tags.findByIds([personal.id, ofTrip.id]);
|
||||
|
||||
expect(rows.sort((a, b) => a.id - b.id)).toEqual(
|
||||
[
|
||||
{ id: personal.id, user_id: user.id, trip_id: null },
|
||||
{ id: ofTrip.id, user_id: user.id, trip_id: trip.id },
|
||||
].sort((a, b) => a.id - b.id),
|
||||
);
|
||||
});
|
||||
|
||||
it('FINDBYIDSREPO-001: returns id + user_id for the matching ids, empty input short-circuits', async () => {
|
||||
const { user: ownerA } = createUser(testDb);
|
||||
const { user: ownerB } = createUser(testDb, { username: 'owner_b' });
|
||||
|
||||
@@ -561,6 +561,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
is_archived: 0,
|
||||
cover_image: null,
|
||||
reminder_days: 3,
|
||||
costs_mode: 'split',
|
||||
});
|
||||
// Seen INSIDE the open transaction — the write and the read share
|
||||
// one connection.
|
||||
@@ -610,6 +611,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
|
||||
is_archived: 1,
|
||||
cover_image: 'c.png',
|
||||
reminder_days: 7,
|
||||
costs_mode: 'totals',
|
||||
});
|
||||
const row = await tripRow(trip.id);
|
||||
expect(row).toMatchObject({
|
||||
@@ -621,6 +623,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
|
||||
is_archived: 1,
|
||||
cover_image: 'c.png',
|
||||
reminder_days: 7,
|
||||
costs_mode: 'totals',
|
||||
});
|
||||
// CURRENT_TIMESTAMP has one-second resolution — a same-second before/after
|
||||
// comparison is flaky, not a real assertion; the column being non-null and
|
||||
@@ -648,7 +651,7 @@ describe('TripsRepository.insertTrip / updateTripRow / setCoverImage / deleteByI
|
||||
// ── Plan 3c Task 8 (`TripsService.copy`, TP37) — additive ───────────────────
|
||||
|
||||
describe('TripsRepository.insertTripCopy (TP37)', () => {
|
||||
it('TRIPREPO-039: writes the 8-column copy set, is_archived hard-coded to 0 regardless of the caller', async () => {
|
||||
it('TRIPREPO-039: writes the 9-column copy set, is_archived hard-coded to 0 regardless of the caller', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: newOwner } = createUser(testDb);
|
||||
const newId = await trips.insertTripCopy({
|
||||
@@ -660,9 +663,20 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
|
||||
currency: 'USD',
|
||||
cover_image: 'c.png',
|
||||
reminder_days: 7,
|
||||
costs_mode: 'totals',
|
||||
});
|
||||
const { user_id, title, description, start_date, end_date, currency, cover_image, is_archived, reminder_days } =
|
||||
await tripRow(newId);
|
||||
const {
|
||||
user_id,
|
||||
title,
|
||||
description,
|
||||
start_date,
|
||||
end_date,
|
||||
currency,
|
||||
cover_image,
|
||||
is_archived,
|
||||
reminder_days,
|
||||
costs_mode,
|
||||
} = await tripRow(newId);
|
||||
const row = {
|
||||
user_id,
|
||||
title,
|
||||
@@ -673,6 +687,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
|
||||
cover_image,
|
||||
is_archived,
|
||||
reminder_days,
|
||||
costs_mode,
|
||||
};
|
||||
expect(row).toEqual({
|
||||
user_id: newOwner.id,
|
||||
@@ -684,6 +699,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
|
||||
cover_image: 'c.png',
|
||||
is_archived: 0,
|
||||
reminder_days: 7,
|
||||
costs_mode: 'totals',
|
||||
});
|
||||
// The source trip (never touched) proves is_archived: 0 is a literal, not a copied value.
|
||||
await setTrip(owner.id, { is_archived: 1 });
|
||||
@@ -702,6 +718,7 @@ describe('TripsRepository.insertTripCopy (TP37)', () => {
|
||||
currency: null,
|
||||
cover_image: null,
|
||||
reminder_days: 3,
|
||||
costs_mode: 'split',
|
||||
});
|
||||
expect((await tripRow(newId)).is_archived).toBe(0);
|
||||
});
|
||||
|
||||
@@ -669,6 +669,25 @@ describe('UsersRepository', () => {
|
||||
expect(row.updated_at).toBe('2020-01-01 00:00:00');
|
||||
});
|
||||
|
||||
it('USERSREPO-088: linkOidcIdentity with nulls removes the SSO link WITHOUT touching updated_at (#3065)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(
|
||||
t,
|
||||
Users,
|
||||
{ id: user.id },
|
||||
{ oidc_sub: 'sub-1', oidc_issuer: 'https://idp.example.com', updated_at: '2020-01-01 00:00:00' },
|
||||
);
|
||||
await users.linkOidcIdentity(user.id, null, null);
|
||||
const row = (await findRow(t, Users, { id: user.id })) as {
|
||||
oidc_sub: string | null;
|
||||
oidc_issuer: string | null;
|
||||
updated_at: string;
|
||||
};
|
||||
expect(row.oidc_sub).toBeNull();
|
||||
expect(row.oidc_issuer).toBeNull();
|
||||
expect(row.updated_at).toBe('2020-01-01 00:00:00');
|
||||
});
|
||||
|
||||
it('USERSREPO-042: setRole (O8) writes role WITHOUT touching updated_at', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(t, Users, { id: user.id }, { updated_at: '2020-01-01 00:00:00' });
|
||||
|
||||
@@ -41,13 +41,15 @@ const AT6 = (n: number) => `
|
||||
WHERE r.trip_id IN (${Array(n).fill('?').join(',')}) AND e.role IN ('from', 'to')
|
||||
AND ${TRAVELER_OWNS}`;
|
||||
|
||||
// AT45 also names the trip's last day since #2648, the dashboard's order of countries.
|
||||
const AT45 = `
|
||||
SELECT DISTINCT e.id, e.reservation_id, r.trip_id, e.role, e.code, e.lat, e.lng, e.local_date, e.local_time,
|
||||
r.type AS reservation_type, r.status AS reservation_status,
|
||||
CASE e.role
|
||||
WHEN 'to' THEN COALESCE(r.reservation_end_time, r.reservation_time)
|
||||
ELSE COALESCE(r.reservation_time, r.reservation_end_time)
|
||||
END AS fallback_time
|
||||
END AS fallback_time,
|
||||
COALESCE(t.end_date, t.start_date) AS trip_last_date
|
||||
FROM reservation_endpoints e
|
||||
JOIN reservations r ON e.reservation_id = r.id
|
||||
JOIN trips t ON r.trip_id = t.id
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* `Migration20200101046440_a_trip_owns_its_tags`: a tag can belong to a trip.
|
||||
* Every tag from before stays a personal one, a trip's tag has to name a real
|
||||
* trip, and it goes with that trip, taking itself off the places that carried it.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101046440_a_trip_owns_its_tags';
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
const names = await pendingNames(orm);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(orm, names[index - 1]);
|
||||
return orm;
|
||||
}
|
||||
|
||||
describe('a trip owns its tags', () => {
|
||||
it('TRIPTAG-MIG-001: keeps every existing tag personal, on the places it was on', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
|
||||
);
|
||||
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon')");
|
||||
await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower')");
|
||||
await rawExec(orm, "INSERT INTO tags (id, user_id, name, color) VALUES (30, 1, 'hidden gem', '#ff0000')");
|
||||
await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30)');
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await rawQuery(orm, 'SELECT id, user_id, trip_id, name, color FROM tags')).toEqual([
|
||||
{ id: 30, user_id: 1, trip_id: null, name: 'hidden gem', color: '#ff0000' },
|
||||
]);
|
||||
expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags')).toEqual([{ place_id: 20, tag_id: 30 }]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('TRIPTAG-MIG-002: a tag of a trip names a real trip and goes when the trip goes', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')",
|
||||
);
|
||||
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon'), (11, 1, 'Porto')");
|
||||
await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower'), (21, 11, 'Ribeira')");
|
||||
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (30, 1, 10, 'Monument')");
|
||||
await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (31, 1, 11, 'Zone')");
|
||||
await rawExec(orm, "INSERT INTO tags (id, user_id, name) VALUES (32, 1, 'personal')");
|
||||
await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30), (21, 31), (21, 32)');
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO tags (user_id, trip_id, name) VALUES (1, 999, 'Nowhere')"),
|
||||
).rejects.toThrow(/FOREIGN KEY/);
|
||||
|
||||
await rawExec(orm, 'DELETE FROM trips WHERE id = 10');
|
||||
|
||||
expect(await rawQuery(orm, 'SELECT id, trip_id FROM tags ORDER BY id')).toEqual([
|
||||
{ id: 31, trip_id: 11 },
|
||||
{ id: 32, trip_id: null },
|
||||
]);
|
||||
expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags ORDER BY tag_id')).toEqual([
|
||||
{ place_id: 21, tag_id: 31 },
|
||||
{ place_id: 21, tag_id: 32 },
|
||||
]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('TRIPTAG-MIG-003: the trip column is indexed, so deleting a trip does not scan every tag', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await migrateTo(orm, TARGET);
|
||||
const indexes = await rawQuery<{ name: string }>(orm, "SELECT name FROM pragma_index_list('tags')");
|
||||
expect(indexes.map((index) => index.name)).toContain('idx_tags_trip_id');
|
||||
expect(await rawQuery(orm, "SELECT name FROM pragma_index_info('idx_tags_trip_id')")).toEqual([
|
||||
{ name: 'trip_id' },
|
||||
]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -61,16 +61,27 @@ describe('entrypoint script', () => {
|
||||
|
||||
it('never walks the volumes on a start where they already belong to node', () => {
|
||||
// Only the dir and its direct entries are looked at, never the whole tree.
|
||||
expect(code).toContain('find "$dir" -maxdepth 1 \\( ! -user node -o ! -group node \\) -print -quit');
|
||||
expect(code).toContain('find "$dir" -maxdepth 1 \\( ! -user node -o -group 0 \\) -print -quit');
|
||||
expect(code).not.toMatch(/find "\$dir" \\\(/);
|
||||
// The recursive hand-over sits behind that check and behind a chown of the dir that worked.
|
||||
const check = code.indexOf('-maxdepth 1');
|
||||
const dirChown = code.indexOf('if chown node:node "$dir"');
|
||||
const dirChown = code.indexOf('if chown node "$dir"');
|
||||
expect(dirChown).toBeGreaterThan(check);
|
||||
expect(code.indexOf('chown -R')).toBeGreaterThan(dirChown);
|
||||
expect(code.indexOf('find "$dir" -group 0 -exec chgrp -h node {} +')).toBeGreaterThan(code.indexOf('chown -R'));
|
||||
expect(code).toContain('Correcting ownership of $dir for the node user...');
|
||||
});
|
||||
|
||||
// A Kubernetes fsGroup other than 1000 gives every file that gid. Handing the
|
||||
// group back to node would leave the kubelet's OnRootMismatch with a mismatched
|
||||
// root on the next start, and the two recursive walks would undo each other on
|
||||
// every start (#2918 again). So only the user is taken over, plus a root group.
|
||||
it('takes over the owning user and a root group, never a foreign fsGroup', () => {
|
||||
expect(code).not.toContain('-group node');
|
||||
expect(code).not.toContain('node:node');
|
||||
expect(code).toContain('chown -R -h node "$dir"');
|
||||
});
|
||||
|
||||
it('says so once instead of walking a volume that refuses chown', () => {
|
||||
expect(code).toContain('cannot be handed to the node user (chown refused); run the container as uid 1000 instead.');
|
||||
});
|
||||
|
||||
@@ -110,7 +110,31 @@ describe('Tool: assign_place_to_day', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('MDT-MCP-001: puts one stage of a multi-day tour on a day, refusing as REST does', async () => {
|
||||
it('set_assignment_stay: changes the stay of one visit and leaves the other visit of the place alone (#3092)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const first = createDayAssignment(testDb, day.id, place.id);
|
||||
const second = createDayAssignment(testDb, day.id, place.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const changed = await h.client.callTool({
|
||||
name: 'set_assignment_stay',
|
||||
arguments: { tripId: trip.id, assignmentId: second.id, stay_minutes: 5 },
|
||||
});
|
||||
expect(parseToolResult(changed)).toMatchObject({ assignment: { id: second.id, stay_minutes: 5 } });
|
||||
const other = createTrip(testDb, user.id);
|
||||
const refused = await h.client.callTool({
|
||||
name: 'set_assignment_stay',
|
||||
arguments: { tripId: other.id, assignmentId: second.id, stay_minutes: 5 },
|
||||
});
|
||||
expect(refused.isError).toBe(true);
|
||||
});
|
||||
const rows = await findRows(orm, DayAssignments, { id: { $in: [first.id, second.id] } }, { id: 'asc' });
|
||||
expect(rows.map((r) => r.stay_minutes)).toEqual([null, 5]);
|
||||
});
|
||||
|
||||
it('MDT-MCP-001:puts one stage of a multi-day tour on a day, refusing as REST does', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Unit tests for MCP collab polls and chat tools (collab addon-gated):
|
||||
* Unit tests for MCP collab polls, chat and link tools (collab addon-gated):
|
||||
* list_collab_polls, create_collab_poll, vote_collab_poll, close_collab_poll,
|
||||
* delete_collab_poll, list_collab_messages, send_collab_message,
|
||||
* delete_collab_message, react_collab_message (CollabMcp, DI-discovered —
|
||||
@@ -8,18 +8,21 @@
|
||||
*/
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { CollabLinks } from '../../../src/db/entities/CollabLinks.entity';
|
||||
import { CollabPollVotes } from '../../../src/db/entities/CollabPollVotes.entity';
|
||||
import { CollabPolls } from '../../../src/db/entities/CollabPolls.entity';
|
||||
import { TripMembers } from '../../../src/db/entities/TripMembers.entity';
|
||||
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
|
||||
import { createUser, createTrip } from '../../helpers/factories';
|
||||
import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';
|
||||
import { addTripMember, createUser, createTrip } from '../../helpers/factories';
|
||||
import { makeCollabMessage } from '../../helpers/factories/collab';
|
||||
import { countRows, findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { setAppSetting } from '../../helpers/factories/settings';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
import { bootTestApp } from '../../helpers/test-app';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { setAddonEnabled } from '../../helpers/test-db';
|
||||
import { setAddonEnabled, setCollabFeature } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
@@ -561,3 +564,305 @@ describe('send_collab_message, as the chat posts it', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The collab link tools (#3076): list_collab_links, create_collab_link,
|
||||
* update_collab_link and delete_collab_link. They are the Links panel's REST
|
||||
* routes as tools, so these cases pin the same rules: trip access for every
|
||||
* call, collab_edit for the writes, the http(s) contract of the shared body
|
||||
* schemas, the collab:link:* broadcasts, and the links flag hiding all four.
|
||||
*/
|
||||
describe('Collab link tools (#3076)', () => {
|
||||
beforeEach(async () => {
|
||||
setAddonEnabled(testDb, ADDON_IDS.COLLAB, true);
|
||||
// resetTestDb truncates app_settings, but the permission cache is module-scoped
|
||||
// and would keep serving whatever the previous case configured.
|
||||
await invalidatePermissionsCache();
|
||||
});
|
||||
|
||||
type ToolResult = Awaited<ReturnType<McpHarness['client']['callTool']>>;
|
||||
|
||||
async function call(userId: number, name: string, args: Record<string, unknown>): Promise<ToolResult> {
|
||||
const h = await createMcpHarness({ realtime, userId, withResources: false });
|
||||
try {
|
||||
return await h.client.callTool({ name, arguments: args });
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function toolNames(userId: number): Promise<string[]> {
|
||||
const h = await createMcpHarness({ realtime, userId, withResources: false });
|
||||
try {
|
||||
return (await h.client.listTools()).tools.map((tool) => tool.name);
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
function insertLink(tripId: number, userId: number, title = 'Ferry', pinned = 0): Promise<number> {
|
||||
return insertRow(orm, CollabLinks, { trip: tripId, user: userId, title, url: 'https://example.com/ferry', pinned });
|
||||
}
|
||||
|
||||
function linkRow(id: number) {
|
||||
return findRow(orm, CollabLinks, { id });
|
||||
}
|
||||
|
||||
/** A member of the owner's trip, once collab_edit is lowered to the owner alone. */
|
||||
async function memberWithoutEdit() {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, member.id);
|
||||
await setAppSetting(orm, 'perm_collab_edit', 'trip_owner');
|
||||
await invalidatePermissionsCache();
|
||||
return { owner, member, trip };
|
||||
}
|
||||
|
||||
const LINK_TOOLS = ['list_collab_links', 'create_collab_link', 'update_collab_link', 'delete_collab_link'];
|
||||
|
||||
describe('Tool: list_collab_links', () => {
|
||||
it('MCP-COLLAB-LINK-001: lists the links pinned first, then newest first, with their author', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await insertLink(trip.id, user.id, 'Timetable');
|
||||
const pinned = await insertLink(trip.id, user.id, 'Hotel', 1);
|
||||
const data = parseToolResult(await call(user.id, 'list_collab_links', { tripId: trip.id })) as {
|
||||
links: Array<Record<string, unknown>>;
|
||||
};
|
||||
expect(data.links.map((link) => link.title)).toEqual(['Hotel', 'Timetable']);
|
||||
expect(data.links[0]).toMatchObject({ id: pinned, pinned: 1, username: user.username });
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-002: refuses a trip the user is not part of', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: owner } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
await insertLink(trip.id, owner.id);
|
||||
expect((await call(user.id, 'list_collab_links', { tripId: trip.id })).isError).toBe(true);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-003: is a read a member may make without collab_edit', async () => {
|
||||
const { owner, member, trip } = await memberWithoutEdit();
|
||||
await insertLink(trip.id, owner.id);
|
||||
const result = await call(member.id, 'list_collab_links', { tripId: trip.id });
|
||||
expect(result.isError).toBeFalsy();
|
||||
expect((parseToolResult(result) as { links: unknown[] }).links).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: create_collab_link', () => {
|
||||
it('MCP-COLLAB-LINK-004: saves the link with the caller as author and broadcasts it', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const result = await call(user.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: ' Ferry tickets ',
|
||||
url: 'https://example.com/ferry',
|
||||
pinned: true,
|
||||
});
|
||||
const { link } = parseToolResult(result) as { link: Record<string, unknown> };
|
||||
expect(link).toMatchObject({
|
||||
trip_id: trip.id,
|
||||
user_id: user.id,
|
||||
title: 'Ferry tickets',
|
||||
url: 'https://example.com/ferry',
|
||||
pinned: 1,
|
||||
username: user.username,
|
||||
});
|
||||
expect(broadcastMock).toHaveBeenCalledWith(
|
||||
trip.id,
|
||||
'collab:link:created',
|
||||
expect.objectContaining({ link: expect.objectContaining({ id: link.id }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-005: leaves a link unpinned unless asked', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const result = await call(user.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: 'Map',
|
||||
url: 'https://example.com/map',
|
||||
});
|
||||
expect((parseToolResult(result) as { link: { pinned: number } }).link.pinned).toBe(0);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-006: refuses a URL that is not http(s), or an empty title, like the REST route', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const refused = await Promise.all(
|
||||
[
|
||||
{ title: 'Script', url: 'javascript:alert(1)' },
|
||||
{ title: 'Mail', url: 'mailto:someone@example.com' },
|
||||
{ title: ' ', url: 'https://example.com' },
|
||||
].map((args) => call(user.id, 'create_collab_link', { tripId: trip.id, ...args })),
|
||||
);
|
||||
expect(refused.every((r) => r.isError)).toBe(true);
|
||||
expect(await countRows(orm, CollabLinks, { trip: trip.id })).toBe(0);
|
||||
expect(broadcastMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-007: refuses a member without collab_edit and saves nothing', async () => {
|
||||
const { member, trip } = await memberWithoutEdit();
|
||||
const result = await call(member.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: 'Ferry',
|
||||
url: 'https://example.com/ferry',
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(await countRows(orm, CollabLinks, { trip: trip.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-008: refuses a trip the user is not part of', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: owner } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
const result = await call(user.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: 'Ferry',
|
||||
url: 'https://example.com/ferry',
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(await countRows(orm, CollabLinks, { trip: trip.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-009: blocks the demo user', async () => {
|
||||
process.env.DEMO_MODE = 'true';
|
||||
const { user } = createUser(testDb, { email: 'demo@nomad.app' });
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const result = await call(user.id, 'create_collab_link', {
|
||||
tripId: trip.id,
|
||||
title: 'Ferry',
|
||||
url: 'https://example.com/ferry',
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: update_collab_link', () => {
|
||||
it('MCP-COLLAB-LINK-010: changes only the fields given and broadcasts the link', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const id = await insertLink(trip.id, user.id, 'Ferry');
|
||||
const result = await call(user.id, 'update_collab_link', { tripId: trip.id, linkId: id, pinned: true });
|
||||
expect((parseToolResult(result) as { link: Record<string, unknown> }).link).toMatchObject({
|
||||
id,
|
||||
title: 'Ferry',
|
||||
url: 'https://example.com/ferry',
|
||||
pinned: 1,
|
||||
});
|
||||
expect(broadcastMock).toHaveBeenCalledWith(
|
||||
trip.id,
|
||||
'collab:link:updated',
|
||||
expect.objectContaining({ link: expect.objectContaining({ id }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-011: renames, moves and unpins a link', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const id = await insertLink(trip.id, user.id, 'Ferry', 1);
|
||||
await call(user.id, 'update_collab_link', {
|
||||
tripId: trip.id,
|
||||
linkId: id,
|
||||
title: 'Night ferry',
|
||||
url: 'https://example.com/night-ferry',
|
||||
pinned: false,
|
||||
});
|
||||
expect(await linkRow(id)).toMatchObject({
|
||||
title: 'Night ferry',
|
||||
url: 'https://example.com/night-ferry',
|
||||
pinned: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-012: says the link is not found when it belongs to another trip, and leaves it alone', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const id = await insertLink(other.id, user.id, 'Ferry');
|
||||
const result = await call(user.id, 'update_collab_link', { tripId: trip.id, linkId: id, title: 'Moved' });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(JSON.stringify(result.content)).toContain('Link not found.');
|
||||
expect((await linkRow(id))?.title).toBe('Ferry');
|
||||
expect(broadcastMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-013: refuses a URL that is not http(s)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const id = await insertLink(trip.id, user.id);
|
||||
const result = await call(user.id, 'update_collab_link', {
|
||||
tripId: trip.id,
|
||||
linkId: id,
|
||||
url: 'ftp://example.com',
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect((await linkRow(id))?.url).toBe('https://example.com/ferry');
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-014: refuses a member without collab_edit', async () => {
|
||||
const { owner, member, trip } = await memberWithoutEdit();
|
||||
const id = await insertLink(trip.id, owner.id);
|
||||
const result = await call(member.id, 'update_collab_link', { tripId: trip.id, linkId: id, title: 'Mine' });
|
||||
expect(result.isError).toBe(true);
|
||||
expect((await linkRow(id))?.title).toBe('Ferry');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tool: delete_collab_link', () => {
|
||||
it('MCP-COLLAB-LINK-015: removes the link and broadcasts its id', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const id = await insertLink(trip.id, user.id);
|
||||
const result = await call(user.id, 'delete_collab_link', { tripId: trip.id, linkId: id });
|
||||
expect(parseToolResult(result)).toEqual({ success: true });
|
||||
expect(await linkRow(id)).toBeNull();
|
||||
expect(broadcastMock).toHaveBeenCalledWith(
|
||||
trip.id,
|
||||
'collab:link:deleted',
|
||||
expect.objectContaining({ linkId: id }),
|
||||
);
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-016: says the link is not found for a link of another trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const other = createTrip(testDb, user.id);
|
||||
const id = await insertLink(other.id, user.id);
|
||||
const result = await call(user.id, 'delete_collab_link', { tripId: trip.id, linkId: id });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(await linkRow(id)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-017: refuses a member without collab_edit', async () => {
|
||||
const { owner, member, trip } = await memberWithoutEdit();
|
||||
const id = await insertLink(trip.id, owner.id);
|
||||
expect((await call(member.id, 'delete_collab_link', { tripId: trip.id, linkId: id })).isError).toBe(true);
|
||||
expect(await linkRow(id)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Collab link tools, gating', () => {
|
||||
it('MCP-COLLAB-LINK-018: are offered only while the links are switched on', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect(await toolNames(user.id)).toEqual(expect.arrayContaining(LINK_TOOLS));
|
||||
setCollabFeature(testDb, 'links', false);
|
||||
try {
|
||||
const names = await toolNames(user.id);
|
||||
expect(names.filter((name) => LINK_TOOLS.includes(name))).toEqual([]);
|
||||
expect(names).toContain('list_collab_notes');
|
||||
} finally {
|
||||
setCollabFeature(testDb, 'links', true);
|
||||
}
|
||||
});
|
||||
|
||||
it('MCP-COLLAB-LINK-019: are gone with the collab addon', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
setAddonEnabled(testDb, ADDON_IDS.COLLAB, false);
|
||||
const names = await toolNames(user.id);
|
||||
expect(names.filter((name) => LINK_TOOLS.includes(name))).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -524,6 +524,15 @@ describe('Tool: update_collection_place / set_collection_place_status / rate_col
|
||||
) as { place: { status: string } };
|
||||
expect(status.place.status).toBe('want');
|
||||
|
||||
// #2567: "want to revisit" is stored as a status of its own.
|
||||
const revisit = parseToolResult(
|
||||
await h.client.callTool({
|
||||
name: 'set_collection_place_status',
|
||||
arguments: { placeId: pid, status: 'revisit' },
|
||||
}),
|
||||
) as { place: { status: string } };
|
||||
expect(revisit.place.status).toBe('revisit');
|
||||
|
||||
const rated = parseToolResult(
|
||||
await h.client.callTool({ name: 'rate_collection_place', arguments: { placeId: pid, rating: 5 } }),
|
||||
) as { place: { rating_avg: number | null; rating_count: number } };
|
||||
@@ -556,6 +565,51 @@ describe('Tool: update_collection_place / set_collection_place_status / rate_col
|
||||
});
|
||||
expect((await findRow(orm, CollectionPlaces, { id: pid }))?.collection_id).toBe(shared);
|
||||
});
|
||||
|
||||
// #2646: the fields saving takes, through the same contract and checks as REST.
|
||||
it('update_collection_place sets and clears provider ids, website, phone and price, and refuses a script link', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const col = await seedCollection(user.id, 'Listings');
|
||||
const pid = await seedPlace(col, user.id, 'Septime');
|
||||
const update = (h: McpHarness, args: Record<string, unknown>) =>
|
||||
h.client.callTool({ name: 'update_collection_place', arguments: { placeId: pid, ...args } });
|
||||
await withHarness(user.id, async (h) => {
|
||||
const set = parseToolResult(
|
||||
await update(h, {
|
||||
google_place_id: 'ChIJseptime',
|
||||
osm_id: 'node/42',
|
||||
website: 'septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
price: 55,
|
||||
currency: 'EUR',
|
||||
}),
|
||||
) as { place: Record<string, unknown> };
|
||||
expect(set.place).toMatchObject({
|
||||
name: 'Septime',
|
||||
google_place_id: 'ChIJseptime',
|
||||
osm_id: 'node/42',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
price: 55,
|
||||
currency: 'EUR',
|
||||
});
|
||||
|
||||
const refused = await update(h, { website: 'javascript:alert(1)' });
|
||||
expect(refused.isError).toBe(true);
|
||||
expect((refused.content as { text: string }[])[0].text).toContain('Invalid arguments');
|
||||
|
||||
const cleared = parseToolResult(await update(h, { website: null, phone: null, price: null })) as {
|
||||
place: Record<string, unknown>;
|
||||
};
|
||||
expect(cleared.place).toMatchObject({
|
||||
website: null,
|
||||
phone: null,
|
||||
price: null,
|
||||
currency: 'EUR',
|
||||
google_place_id: 'ChIJseptime',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -940,6 +994,143 @@ describe('Sharing tools', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_collection_places (#2647): a long list a compact page at a time, going
|
||||
// on from a cursor rather than an offset.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: list_collection_places', () => {
|
||||
interface Page {
|
||||
collection: { id: number; name: string };
|
||||
labels: { id: number; name: string; color: string | null }[];
|
||||
total: number;
|
||||
places: Record<string, unknown>[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
async function listPage(h: McpHarness, args: Record<string, unknown>): Promise<Page> {
|
||||
const result = await h.client.callTool({ name: 'list_collection_places', arguments: args });
|
||||
expect(result.isError).toBeFalsy();
|
||||
// Compact on purpose: one line of JSON, however long the page.
|
||||
expect(errorText(result)).not.toContain('\n');
|
||||
return parseToolResult(result) as Page;
|
||||
}
|
||||
|
||||
async function seedPlaces(colId: number, ownerId: number, count: number): Promise<number[]> {
|
||||
// One after the other, so the ids follow the names.
|
||||
return Array.from({ length: count }, (_, i) => i + 1).reduce<Promise<number[]>>(
|
||||
async (done, n) => [...(await done), await seedPlace(colId, ownerId, `Spot ${n}`)],
|
||||
Promise.resolve([]),
|
||||
);
|
||||
}
|
||||
|
||||
it('MCP-COLL-PAGE-001: pages through a list in its order, compact rows leaving out what a place lacks', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const col = await seedCollection(user.id, 'Paris');
|
||||
await seedPlaces(col, user.id, 4);
|
||||
await seedPlace(col, user.id, 'Septime', { lat: 48.85, lng: 2.38, status: 'want', google_place_id: 'ChIJseptime' });
|
||||
const food = await insertRow(orm, CollectionLabels, { collection: col, name: 'Food', color: '#e11d48' });
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const first = await listPage(h, { collectionId: col, limit: 2 });
|
||||
expect(first.collection).toEqual({ id: col, name: 'Paris' });
|
||||
expect(first.labels).toEqual([{ id: food, name: 'Food', color: '#e11d48' }]);
|
||||
expect(first.total).toBe(5);
|
||||
expect(first.places).toEqual([
|
||||
{ id: expect.any(Number), name: 'Spot 1', status: 'idea' },
|
||||
{ id: expect.any(Number), name: 'Spot 2', status: 'idea' },
|
||||
]);
|
||||
expect(first.next_cursor).toEqual(expect.any(String));
|
||||
|
||||
const second = await listPage(h, { collectionId: col, limit: 2, cursor: first.next_cursor });
|
||||
expect(second.places.map((p) => p.name)).toEqual(['Spot 3', 'Spot 4']);
|
||||
|
||||
const last = await listPage(h, { collectionId: col, limit: 2, cursor: second.next_cursor });
|
||||
expect(last.places).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
name: 'Septime',
|
||||
status: 'want',
|
||||
lat: 48.85,
|
||||
lng: 2.38,
|
||||
google_place_id: 'ChIJseptime',
|
||||
},
|
||||
]);
|
||||
expect(last.next_cursor).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('MCP-COLL-PAGE-002: labelling each page while paging through the unlabeled places skips none', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const col = await seedCollection(user.id, 'Long list');
|
||||
const ids = await seedPlaces(col, user.id, 6);
|
||||
const done = await insertRow(orm, CollectionLabels, { collection: col, name: 'Done' });
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const seen: unknown[] = [];
|
||||
const totals: number[] = [];
|
||||
// Page by page, each one labelled before the next is asked for.
|
||||
const walk = async (cursor: string | null): Promise<void> => {
|
||||
const page = await listPage(h, { collectionId: col, limit: 2, unlabeled: true, ...(cursor ? { cursor } : {}) });
|
||||
totals.push(page.total);
|
||||
seen.push(...page.places.map((p) => p.id));
|
||||
const labelled = await h.client.callTool({
|
||||
name: 'assign_collection_labels',
|
||||
arguments: { label_ids: [done], place_ids: page.places.map((p) => p.id) },
|
||||
});
|
||||
expect(labelled.isError).toBeFalsy();
|
||||
if (page.next_cursor) await walk(page.next_cursor);
|
||||
};
|
||||
await walk(null);
|
||||
// An offset would have jumped from the second place straight to the fifth.
|
||||
expect(seen).toEqual(ids);
|
||||
expect(totals).toEqual([6, 4, 2]);
|
||||
|
||||
const labelled = await listPage(h, { collectionId: col, labelId: done });
|
||||
expect(labelled.total).toBe(6);
|
||||
expect(labelled.places.every((p) => (p.label_ids as number[]).includes(done))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('MCP-COLL-PAGE-003: filters by status, and refuses a foreign label, both label filters at once and a made-up cursor', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const col = await seedCollection(user.id, 'Paris');
|
||||
const elsewhere = await seedCollection(other.id, 'Theirs');
|
||||
await seedPlace(col, user.id, 'Louvre', { status: 'visited' });
|
||||
await seedPlace(col, user.id, 'Orsay', { status: 'revisit' });
|
||||
const theirs = await insertRow(orm, CollectionLabels, { collection: elsewhere, name: 'Theirs' });
|
||||
const mine = await insertRow(orm, CollectionLabels, { collection: col, name: 'Mine' });
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const revisit = await listPage(h, { collectionId: col, status: 'revisit' });
|
||||
expect(revisit.total).toBe(1);
|
||||
expect(revisit.places.map((p) => p.name)).toEqual(['Orsay']);
|
||||
|
||||
const call = (args: Record<string, unknown>) =>
|
||||
h.client.callTool({ name: 'list_collection_places', arguments: { collectionId: col, ...args } });
|
||||
const foreign = await call({ labelId: theirs });
|
||||
expect(foreign.isError).toBe(true);
|
||||
expect(errorText(foreign)).toBe('Label not found in this list');
|
||||
expect(errorText(await call({ labelId: mine, unlabeled: true }))).toBe(
|
||||
'Pass either labelId or unlabeled, not both',
|
||||
);
|
||||
expect(errorText(await call({ cursor: 'not-a-cursor' }))).toBe(
|
||||
'Invalid cursor: pass the next_cursor of the page before',
|
||||
);
|
||||
expect((await call({ limit: 501 })).isError).toBe(true);
|
||||
|
||||
// A list the caller cannot see answers as if it did not exist.
|
||||
const hidden = await h.client.callTool({
|
||||
name: 'list_collection_places',
|
||||
arguments: { collectionId: elsewhere },
|
||||
});
|
||||
expect(hidden.isError).toBe(true);
|
||||
expect(errorText(hidden)).toBe('Collection not found');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scope gating (collections read/write, registration-time)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -947,6 +1138,7 @@ describe('Sharing tools', () => {
|
||||
const READ_TOOLS = [
|
||||
'list_collections',
|
||||
'get_collection',
|
||||
'list_collection_places',
|
||||
'get_collection_items',
|
||||
'available_collection_users',
|
||||
'find_place_in_collections',
|
||||
@@ -987,7 +1179,7 @@ describe('Collection tools — scope gating', () => {
|
||||
}
|
||||
}
|
||||
|
||||
it('registers all 28 tools with null scopes (full access)', async () => {
|
||||
it('registers all 29 tools with null scopes (full access)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const names = await listToolNames(user.id, null);
|
||||
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
|
||||
|
||||
@@ -328,6 +328,25 @@ describe('Tool: disable_all_trips_calendar_feed', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('calendar feed tools, the lean variant (#2602)', () => {
|
||||
it('tell a model how to ask for a feed without the per-day summaries', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const { tools } = await h.client.listTools();
|
||||
for (const name of [
|
||||
'get_trip_calendar_feed',
|
||||
'enable_trip_calendar_feed',
|
||||
'rotate_trip_calendar_feed',
|
||||
'get_all_trips_calendar_feed',
|
||||
'enable_all_trips_calendar_feed',
|
||||
'rotate_all_trips_calendar_feed',
|
||||
]) {
|
||||
expect(tools.find((tool) => tool.name === name)?.description).toContain('?days=0');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('all-trips calendar feed gates', () => {
|
||||
it.each(['enable_all_trips_calendar_feed', 'rotate_all_trips_calendar_feed', 'disable_all_trips_calendar_feed'])(
|
||||
'%s refuses a demo account',
|
||||
|
||||
@@ -1352,6 +1352,42 @@ describe('Tool: export_trip_gpx', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// export_trip_kml (#1866): the places as pins for Google My Maps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: export_trip_kml', () => {
|
||||
it('writes the places as pins and names the file after the trip', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { title: 'Paris Weekend' });
|
||||
createPlace(testDb, trip.id, { name: 'Eiffel Tower', lat: 48.8584, lng: 2.2945 });
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({ name: 'export_trip_kml', arguments: { tripId: trip.id } });
|
||||
const data = parseToolResult(result) as { kml: string; filename: string };
|
||||
expect(data.filename).toBe('Paris-Weekend.kml');
|
||||
expect(data.kml).toContain('<name>Eiffel Tower</name>');
|
||||
expect(data.kml).toContain('<coordinates>2.2945,48.8584</coordinates>');
|
||||
});
|
||||
});
|
||||
|
||||
it('errors when no place has coordinates, and for a non-member', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
const empty = createTrip(testDb, user.id, { title: 'Empty' });
|
||||
const theirs = createTrip(testDb, other.id);
|
||||
createPlace(testDb, theirs.id, { name: 'Theirs', lat: 1, lng: 1 });
|
||||
|
||||
await withHarness(user.id, async (h) => {
|
||||
const nothing = await h.client.callTool({ name: 'export_trip_kml', arguments: { tripId: empty.id } });
|
||||
expect(nothing.isError).toBe(true);
|
||||
expect((nothing.content as { text: string }[])[0].text).toBe('Nothing to export.');
|
||||
const denied = await h.client.callTool({ name: 'export_trip_kml', arguments: { tripId: theirs.id } });
|
||||
expect(denied.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// create_and_assign_place failure path
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -22,7 +22,10 @@ import {
|
||||
createCategory,
|
||||
addTripMember,
|
||||
} from '../../helpers/factories';
|
||||
import { makeReservation } from '../../helpers/factories/reservations';
|
||||
import { countRows, findRow, findRows, insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { makeTrip, readTripDays } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
@@ -93,6 +96,21 @@ describe('Tool: create_reservation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('files the cost of a priced booking under its Costs key when no budget_category is given', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'create_reservation',
|
||||
arguments: { tripId: trip.id, title: 'Jazz night', type: 'event', price: 40 },
|
||||
});
|
||||
const data = parseToolResult(result) as { reservation: { id: number } };
|
||||
const item = await findRow(orm, BudgetItems, { reservation: data.reservation.id });
|
||||
// Not a separate "event" bucket next to other: the key the web form files it under.
|
||||
expect(item?.category).toBe('activities');
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a parking reservation (#1444)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
@@ -221,6 +239,29 @@ describe('Tool: create_reservation', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Tool: update_reservation', () => {
|
||||
// The tool goes through the same update as REST, so an edit that names no day
|
||||
// leaves a time-only booking on the one it has, as a notes-only PUT does.
|
||||
it('keeps the day of a time-only booking on an edit that names no day', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { start_date: '2030-05-01', end_date: '2030-05-03' });
|
||||
const days = await readTripDays(orm, trip.id);
|
||||
const booking = await makeReservation(orm, trip.id, {
|
||||
type: 'restaurant',
|
||||
reservation_time: '19:00',
|
||||
day: days[1].id,
|
||||
});
|
||||
await withHarness(user.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'update_reservation',
|
||||
arguments: { tripId: trip.id, reservationId: booking.id, notes: 'Counter seats' },
|
||||
});
|
||||
expect((parseToolResult(result) as { reservation: { day_id: number | null } }).reservation.day_id).toBe(
|
||||
days[1].id,
|
||||
);
|
||||
});
|
||||
expect((await reservationRow(booking.id)).day_id).toBe(days[1].id);
|
||||
});
|
||||
|
||||
it('updates reservation fields', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
|
||||
@@ -15,7 +15,7 @@ import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { encrypt_api_key } from '../../../src/nest/common/crypto/apiKeyCrypto';
|
||||
import { MANAGED_LOCKED_SETTING_KEYS } from '../../../src/nest/common/managed';
|
||||
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
|
||||
import { DISPLAY_PREFERENCE_KEYS } from '../../../src/nest/settings/settings.mcp';
|
||||
import { DISPLAY_PREFERENCE_KEYS, MAX_DASHBOARD_TIMEZONES } from '../../../src/nest/settings/settings.mcp';
|
||||
import {
|
||||
isAdminOnlyEndpointSetting,
|
||||
ENCRYPTED_SETTING_KEYS,
|
||||
@@ -288,6 +288,44 @@ describe('Tool: update_display_settings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('writes dashboard_timezones as the stored list and reads it back (#3044)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const data = parseToolResult(await update(h, { dashboard_timezones: ['Europe/Madrid', 'Africa/Cairo'] })) as {
|
||||
settings: Record<string, unknown>;
|
||||
};
|
||||
expect(data.settings.dashboard_timezones).toEqual(['Europe/Madrid', 'Africa/Cairo']);
|
||||
expect(await readSetting(user.id, 'dashboard_timezones')).toBe('["Europe/Madrid","Africa/Cairo"]');
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts an empty dashboard_timezones list, which shows no clocks (#3044)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const data = parseToolResult(await update(h, { dashboard_timezones: [] })) as {
|
||||
settings: Record<string, unknown>;
|
||||
};
|
||||
expect(data.settings.dashboard_timezones).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses dashboard_timezones that are unknown, repeated, not a list or too many (#3044)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const tooMany = Intl.supportedValuesOf('timeZone').slice(0, MAX_DASHBOARD_TIMEZONES + 1);
|
||||
await withHarness(user.id, async (h) => {
|
||||
const unknown = await update(h, { dashboard_timezones: ['Europe/Madrid', 'Mars/Olympus_Mons'] });
|
||||
expect(unknown.isError).toBe(true);
|
||||
expect(errorText(unknown)).toContain('IANA');
|
||||
expect((await update(h, { dashboard_timezones: [''] })).isError).toBe(true);
|
||||
expect((await update(h, { dashboard_timezones: ['Asia/Tokyo', 'Asia/Tokyo'] })).isError).toBe(true);
|
||||
expect((await update(h, { dashboard_timezones: 'Europe/Madrid' })).isError).toBe(true);
|
||||
const capped = await update(h, { dashboard_timezones: tooMany });
|
||||
expect(capped.isError).toBe(true);
|
||||
expect(errorText(capped)).toContain(`at most ${MAX_DASHBOARD_TIMEZONES}`);
|
||||
expect(await countSettings(user.id)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts every boolean display preference', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await withHarness(user.id, async (h) => {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';
|
||||
import { Days } from '../../../src/db/entities/Days.entity';
|
||||
import { ShareTokens } from '../../../src/db/entities/ShareTokens.entity';
|
||||
import { TripMembers } from '../../../src/db/entities/TripMembers.entity';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
@@ -13,9 +14,9 @@ import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { GUEST_HAS_PAYMENTS } from '../../../src/nest/budget/budget-departure.helpers';
|
||||
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
|
||||
import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';
|
||||
import { createUser, createAdmin, createTrip, addTripMember } from '../../helpers/factories';
|
||||
import { createUser, createAdmin, createTrip, addTripMember, createDayNote } from '../../helpers/factories';
|
||||
import { addBudgetItemMember, addBudgetItemPayer, makeBudgetItem } from '../../helpers/factories/budget';
|
||||
import { countRows, findRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { countRows, findRow, findRows, updateRows } from '../../helpers/factories/rows';
|
||||
import { setAppSetting } from '../../helpers/factories/settings';
|
||||
import { makeShareToken } from '../../helpers/factories/trips';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
@@ -492,6 +493,26 @@ describe('Tool: export_trip_ics', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves the per-day summaries out with dayEvents false, like days=0 on the route (#2602)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { title: 'Paris Trip', start_date: '2025-06-01', end_date: '2025-06-05' });
|
||||
// A dated trip comes with its days; the first one is the 1st of June.
|
||||
const [day] = await findRows(orm, Days, { trip: trip.id }, { id: 'asc' });
|
||||
createDayNote(testDb, day.id, trip.id, { text: 'Pick up the museum pass' });
|
||||
await withHarness(user.id, async (h) => {
|
||||
const call = async (args: Record<string, unknown>) =>
|
||||
(
|
||||
parseToolResult(
|
||||
await h.client.callTool({ name: 'export_trip_ics', arguments: { tripId: trip.id, ...args } }),
|
||||
) as { ics: string }
|
||||
).ics;
|
||||
expect(await call({})).toContain('SUMMARY:Day 1');
|
||||
const lean = await call({ dayEvents: false });
|
||||
expect(lean).not.toContain('SUMMARY:Day 1');
|
||||
expect(lean).toContain('SUMMARY:Paris Trip');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns access denied for non-member', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const { user: other } = createUser(testDb);
|
||||
|
||||
@@ -1179,4 +1179,35 @@ describe('Trip writes, as REST makes them', () => {
|
||||
});
|
||||
expect(await tripRow(trip.id)).toMatchObject({ title: 'After', is_archived: 1 });
|
||||
});
|
||||
|
||||
it('MCP-TRIPS-005: update_trip sets the costs mode on budget_edit, as the route does (#1714)', async () => {
|
||||
const { user: owner } = createUser(testDb);
|
||||
const { user: member } = createUser(testDb);
|
||||
const trip = createTrip(testDb, owner.id);
|
||||
addTripMember(testDb, trip.id, member.id);
|
||||
expect((await tripRow(trip.id)).costs_mode).toBe('split');
|
||||
// A member may edit the costs by default, though not the trip's own details.
|
||||
await withHarness(member.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'update_trip',
|
||||
arguments: { tripId: trip.id, costs_mode: 'totals' },
|
||||
});
|
||||
expect(result.isError).toBeFalsy();
|
||||
expect((parseToolResult(result) as { trip: { costs_mode: string } }).trip.costs_mode).toBe('totals');
|
||||
});
|
||||
await setPermission('budget_edit', 'trip_owner');
|
||||
await withHarness(member.id, async (h) => {
|
||||
const result = await h.client.callTool({
|
||||
name: 'update_trip',
|
||||
arguments: { tripId: trip.id, costs_mode: 'split' },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const bogus = await h.client.callTool({
|
||||
name: 'update_trip',
|
||||
arguments: { tripId: trip.id, costs_mode: 'shares' },
|
||||
});
|
||||
expect(bogus.isError).toBe(true);
|
||||
});
|
||||
expect((await tripRow(trip.id)).costs_mode).toBe('totals');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,6 +114,14 @@ describe('global CSP: the imagery host (#2307)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('global CSP: the iOS app tile store', () => {
|
||||
it('allows trek-tile: images, or the app draws routes on a blank map', async () => {
|
||||
// The app rewrites raster tiles to trek-tile:// (client/src/native/tileCache.ts)
|
||||
// and answers them from its store; WebKit checks that scheme against img-src.
|
||||
expect(await directiveSources('img-src')).toContain('trek-tile:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('global CSP: the elevation tiles of the 3D tour view', () => {
|
||||
it('allows the Terrarium tiles, which MapLibre and the flyover preload fetch', async () => {
|
||||
// The 3D view drapes the route over Mapzen's open elevation model on AWS Open
|
||||
|
||||
@@ -33,6 +33,21 @@ describe('globalMiddleware request-log redaction', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('redacts the mail import secrets the admin settings form sends, and keeps the rest readable', () => {
|
||||
const out = redact({
|
||||
mail_ingest_imap_host: 'imap.example.com',
|
||||
mail_ingest_imap_pass: 'box-secret',
|
||||
mail_ingest_webhook_secret: 'hook-secret',
|
||||
mail_ingest_address_template: 'trek+{token}@example.com',
|
||||
});
|
||||
expect(out).toEqual({
|
||||
mail_ingest_imap_host: 'imap.example.com',
|
||||
mail_ingest_imap_pass: '[REDACTED]',
|
||||
mail_ingest_webhook_secret: '[REDACTED]',
|
||||
mail_ingest_address_template: 'trek+{token}@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('redacts nested objects and arrays, leaving non-sensitive fields untouched', () => {
|
||||
const out = redact({
|
||||
name: 'off-box',
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
demoDenied,
|
||||
errorResult,
|
||||
ok,
|
||||
okCompact,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
|
||||
@@ -19,6 +20,12 @@ describe('result helpers', () => {
|
||||
expect('isError' in result).toBe(false);
|
||||
});
|
||||
|
||||
it('okCompact() wraps data as one line of JSON, without isError', () => {
|
||||
const result = okCompact({ a: 1, b: [2, 3] });
|
||||
expect(result).toEqual({ content: [{ type: 'text', text: '{"a":1,"b":[2,3]}' }] });
|
||||
expect('isError' in result).toBe(false);
|
||||
});
|
||||
|
||||
it('errorResult() carries the message verbatim with isError', () => {
|
||||
expect(errorResult('Tag not found.')).toEqual({
|
||||
content: [{ type: 'text', text: 'Tag not found.' }],
|
||||
|
||||
@@ -435,6 +435,22 @@ describe('AddonsService addon/feature flags', () => {
|
||||
expect((await svc.list()).toursWanderer).toBe(false);
|
||||
});
|
||||
|
||||
it('wanderer is never available on a managed install, whatever the stored switch says', async () => {
|
||||
const saved = process.env.TREK_MANAGED;
|
||||
try {
|
||||
await insertAddon({ id: 'tours', name: 'Tours', enabled: 1 });
|
||||
await svc.updateToursWanderer(true);
|
||||
expect(await svc.isWandererAvailable()).toBe(true);
|
||||
|
||||
process.env.TREK_MANAGED = '1';
|
||||
expect(await svc.isWandererAvailable()).toBe(false);
|
||||
expect((await svc.list()).toursWanderer).toBe(false);
|
||||
} finally {
|
||||
if (saved === undefined) delete process.env.TREK_MANAGED;
|
||||
else process.env.TREK_MANAGED = saved;
|
||||
}
|
||||
});
|
||||
|
||||
it('OpenHikingMap under Tours is on until an admin switches it off, and offered only with Tours (MAP-01)', async () => {
|
||||
expect(await svc.getToursHikingMap()).toEqual({ enabled: true }); // absent row → ON
|
||||
expect((await svc.list()).toursHikingMap).toBe(false); // Tours is off
|
||||
|
||||
@@ -357,6 +357,42 @@ describe('AdminController addons + sessions + jwt + defaults', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminController SSO unlink (#3065)', () => {
|
||||
it('ADMIN-CTRL-SSO-001: audits a removed link and answers unlinked: true', async () => {
|
||||
writeAudit.mockClear();
|
||||
const unlinkUserSso = vi.fn().mockResolvedValue({ email: 'a@b.c', unlinked: true });
|
||||
expect(await adminCtl(svc({ unlinkUserSso } as Partial<AdminService>)).unlinkUserSso(user, '4', req)).toEqual({
|
||||
success: true,
|
||||
unlinked: true,
|
||||
});
|
||||
expect(unlinkUserSso).toHaveBeenCalledWith('4', user.id);
|
||||
expect(writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'admin.user_sso_unlink', resource: '4', details: { targetUser: 'a@b.c' } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('ADMIN-CTRL-SSO-002: writes no audit row when there was no link, and maps the self refusal', async () => {
|
||||
writeAudit.mockClear();
|
||||
expect(
|
||||
await adminCtl(
|
||||
svc({ unlinkUserSso: vi.fn().mockResolvedValue({ email: 'a@b.c', unlinked: false }) } as Partial<AdminService>),
|
||||
).unlinkUserSso(user, '4', req),
|
||||
).toEqual({ success: true, unlinked: false });
|
||||
expect(writeAudit).not.toHaveBeenCalled();
|
||||
expect(
|
||||
await thrown(() =>
|
||||
adminCtl(
|
||||
svc({
|
||||
unlinkUserSso: vi
|
||||
.fn()
|
||||
.mockRejectedValue(new DomainError(400, 'You cannot remove the SSO link of your own account')),
|
||||
} as Partial<AdminService>),
|
||||
).unlinkUserSso(user, '1', req),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'You cannot remove the SSO link of your own account' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminController read-only getters', () => {
|
||||
it('return service values verbatim', async () => {
|
||||
expect(
|
||||
|
||||
@@ -998,6 +998,61 @@ describe('resetUserMfa', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// #3065: the provider re-issued a user's subject, so every sign-in hits
|
||||
// "linked to another subject of this provider" and editing the email cannot help.
|
||||
describe('unlinkUserSso', () => {
|
||||
it('ADMIN-SVC-097 — clears sub and issuer so the next SSO sign-in links like a first one', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(orm, Users, { id: user.id }, { oidc_sub: 'sub-old', oidc_issuer: 'https://idp.example.com' });
|
||||
|
||||
const result = await svc.unlinkUserSso(String(user.id), admin.user.id);
|
||||
|
||||
expect(result).toEqual({ email: user.email, unlinked: true });
|
||||
const row = await readUser(orm, user.id);
|
||||
expect({ oidc_sub: row.oidc_sub, oidc_issuer: row.oidc_issuer }).toEqual({ oidc_sub: null, oidc_issuer: null });
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-098 — an account without an SSO link answers unlinked: false and stays as it is', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
expect(await svc.unlinkUserSso(String(user.id), admin.user.id)).toEqual({ email: user.email, unlinked: false });
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-099 — refuses the callers own account and keeps its link', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
await updateRows(
|
||||
orm,
|
||||
Users,
|
||||
{ id: admin.user.id },
|
||||
{ oidc_sub: 'sub-admin', oidc_issuer: 'https://idp.example.com' },
|
||||
);
|
||||
|
||||
const result = (await asLegacyResult(svc.unlinkUserSso(String(admin.user.id), admin.user.id))) as {
|
||||
error?: string;
|
||||
status?: number;
|
||||
};
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/your own/i);
|
||||
expect((await readUser(orm, admin.user.id)).oidc_sub).toBe('sub-admin');
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-100 — 404 for a user that is not there, and for a guest', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user: guest } = createUser(testDb);
|
||||
await updateRows(orm, Users, { id: guest.id }, { is_guest: 1 });
|
||||
|
||||
expect((await asLegacyResult(svc.unlinkUserSso('99999', admin.user.id))) as { status?: number }).toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
expect(
|
||||
(await asLegacyResult(svc.unlinkUserSso(String(guest.id), admin.user.id))) as { status?: number },
|
||||
).toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkVersion on a centrally administered install', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
* decides whose connection a user's assistant runs on, and the instance's
|
||||
* connection keeps a stored key only for the target it was saved for.
|
||||
*
|
||||
* Replaced: the model catalog (no provider is asked), the ChatGPT sign-in, the
|
||||
* addon switch, the demo check, the audit writer and AI parsing's config.
|
||||
* Replaced: the model catalog (no provider is asked), the ChatGPT sign-in and
|
||||
* its chat client, the addon switch, the demo check, the audit writer and AI parsing's config.
|
||||
*/
|
||||
import { AiConnections } from '../../../../src/db/entities/AiConnections.entity';
|
||||
import { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import type { AiChatEvent, AiChatRequest } from '../../../../src/nest/ai-connections/ai-chat-client.interface';
|
||||
import { AiChatClientService } from '../../../../src/nest/ai-connections/ai-chat-client.service';
|
||||
import { AiConnectionsModule } from '../../../../src/nest/ai-connections/ai-connections.module';
|
||||
import { AiConnectionsService } from '../../../../src/nest/ai-connections/ai-connections.service';
|
||||
import { ChatgptAuthService } from '../../../../src/nest/ai-connections/chatgpt-auth.service';
|
||||
@@ -42,6 +44,20 @@ const MODELS: AiModelInfo[] = [
|
||||
|
||||
const catalog = { list: vi.fn(async (): Promise<AiModelInfo[]> => MODELS) };
|
||||
const chatgpt = { accessToken: vi.fn(async () => 'chatgpt-access') };
|
||||
/** What the plan's model answers a parsing read with, and what it was asked. */
|
||||
let planAnswer: AiChatEvent[] = [];
|
||||
const planAsked: AiChatRequest[] = [];
|
||||
const chatClients = {
|
||||
chatgptPlan: vi.fn((_id: number, model: string, _token: string) => ({
|
||||
kind: 'chatgpt' as const,
|
||||
model,
|
||||
webSearch: true,
|
||||
async *stream(request: AiChatRequest) {
|
||||
planAsked.push(request);
|
||||
yield* planAnswer;
|
||||
},
|
||||
})),
|
||||
};
|
||||
const addons = { isAddonEnabled: vi.fn(async () => true) };
|
||||
const demo = { isDemoUserId: vi.fn(async () => false) };
|
||||
const audit = { writeAudit: vi.fn(async () => undefined) };
|
||||
@@ -56,6 +72,7 @@ beforeAll(async () => {
|
||||
overrides: [
|
||||
{ provide: ModelCatalogService, useValue: catalog },
|
||||
{ provide: ChatgptAuthService, useValue: chatgpt },
|
||||
{ provide: AiChatClientService, useValue: chatClients },
|
||||
{ provide: AddonsService, useValue: addons },
|
||||
{ provide: DemoService, useValue: demo },
|
||||
{ provide: AuditService, useValue: audit },
|
||||
@@ -449,21 +466,85 @@ describe('the connection AI parsing shares', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('AICS-031: a ChatGPT plan or a connection with a problem is not lent to parsing', async () => {
|
||||
it('AICS-031: a connection with a problem is not lent to parsing', async () => {
|
||||
const id = await user();
|
||||
const { em } = orm();
|
||||
await em.fork().insert(AiConnections, {
|
||||
scope: 'user',
|
||||
user: id,
|
||||
kind: 'chatgpt',
|
||||
model: 'gpt-6.1-sol',
|
||||
status: 'ok',
|
||||
});
|
||||
expect(await service().forParsing(id)).toBeNull();
|
||||
await em.fork().nativeDelete(AiConnections, { user: id });
|
||||
await service().saveOwnKey(id, { kind: 'openai', apiKey: 'sk-proj-own-parse' });
|
||||
expect(await service().forParsing(id)).toMatchObject({ provider: 'openai', apiKey: 'sk-proj-own-parse' });
|
||||
await em.fork().nativeUpdate(AiConnections, { user: id }, { status: 'error' });
|
||||
expect(await service().forParsing(id)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a ChatGPT plan lent to AI parsing', () => {
|
||||
const READ = {
|
||||
system: 'Read bookings.',
|
||||
text: 'LH 1166 FRA-LIS',
|
||||
images: [{ mimeType: 'image/png' as const, data: 'cGFnZQ==' }],
|
||||
shape: { name: 'record_reservations', description: 'Record them.', parameters: { type: 'object' } },
|
||||
};
|
||||
|
||||
async function planUser(status = 'ok'): Promise<number> {
|
||||
const id = await user();
|
||||
await orm()
|
||||
.em.fork()
|
||||
.insert(AiConnections, { scope: 'user', user: id, kind: 'chatgpt', model: 'gpt-6.1-sol', status });
|
||||
return id;
|
||||
}
|
||||
|
||||
async function lent(id: number) {
|
||||
const connection = await service().forParsing(id);
|
||||
if (connection?.provider !== 'chatgpt') throw new Error('no ChatGPT plan was lent');
|
||||
return connection;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
planAnswer = [];
|
||||
planAsked.length = 0;
|
||||
});
|
||||
|
||||
it('AICS-032: the plan is lent as a reader that makes the model fill the shape as its one tool', async () => {
|
||||
const id = await planUser();
|
||||
const connection = await lent(id);
|
||||
expect(connection).toMatchObject({ provider: 'chatgpt', model: 'gpt-6.1-sol' });
|
||||
expect(chatgpt.accessToken).not.toHaveBeenCalled();
|
||||
|
||||
planAnswer = [
|
||||
{ type: 'tool-call', call: { id: 'c1', name: 'record_reservations', args: { reservations: [{ n: 1 }] } } },
|
||||
{ type: 'tool-call', call: { id: 'c2', name: 'record_reservations', args: { reservations: [{ n: 2 }] } } },
|
||||
{ type: 'finish', reason: 'tool-calls' },
|
||||
];
|
||||
expect(await connection.read({ ...READ, signal: new AbortController().signal })).toEqual({
|
||||
filled: { reservations: [{ n: 1 }] },
|
||||
});
|
||||
expect(chatgpt.accessToken).toHaveBeenCalledTimes(1);
|
||||
expect(chatClients.chatgptPlan).toHaveBeenCalledWith(expect.any(Number), 'gpt-6.1-sol', 'chatgpt-access');
|
||||
expect(planAsked[0]).toEqual({
|
||||
system: 'Read bookings.',
|
||||
messages: [{ role: 'user', text: 'LH 1166 FRA-LIS', images: READ.images }],
|
||||
tools: [READ.shape],
|
||||
toolChoice: 'required',
|
||||
});
|
||||
});
|
||||
|
||||
it('AICS-033: a model that called no tool answers with the text it wrote, whole', async () => {
|
||||
const connection = await lent(await planUser());
|
||||
planAnswer = [
|
||||
{ type: 'text-delta', delta: '{"reservations": ' },
|
||||
{ type: 'text-delta', delta: '[]}' },
|
||||
{ type: 'finish', reason: 'stop' },
|
||||
];
|
||||
expect(await connection.read({ ...READ, signal: new AbortController().signal })).toEqual({
|
||||
text: '{"reservations": []}',
|
||||
});
|
||||
});
|
||||
|
||||
it('AICS-034: a sign-in to renew lends nothing, and a refused token reaches the caller', async () => {
|
||||
expect(await service().forParsing(await planUser('needs_reauth'))).toBeNull();
|
||||
const connection = await lent(await planUser());
|
||||
chatgpt.accessToken.mockRejectedValueOnce(new AiProviderError('needs_reauth', 401, false));
|
||||
await expect(connection.read({ ...READ, signal: new AbortController().signal })).rejects.toBeInstanceOf(
|
||||
AiProviderError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -238,6 +238,23 @@ describe('AnthropicMessagesClient', () => {
|
||||
expect([0, 1, 2, 3].map((i) => dig(body, 'messages', i, 'role'))).toEqual(['user', 'assistant', 'user', undefined]);
|
||||
});
|
||||
|
||||
it('ANTH-009: a text-only request keeps the tools for the history and sets tool_choice none (#3016)', async () => {
|
||||
const http = fetchAnswering(streamResponse(STREAM));
|
||||
await run(
|
||||
new AnthropicMessagesClient('claude-sonnet', 'sk-ant-key', http.fetcher).stream(
|
||||
{ ...REQUEST, toolChoice: 'none' },
|
||||
signal(),
|
||||
),
|
||||
);
|
||||
const body = http.body();
|
||||
expect(body.tool_choice).toEqual({ type: 'none' });
|
||||
expect(dig(body, 'tools', 0, 'name')).toBe('create_place');
|
||||
|
||||
const plain = fetchAnswering(streamResponse(STREAM));
|
||||
await run(new AnthropicMessagesClient('claude-sonnet', 'sk-ant-key', plain.fetcher).stream(REQUEST, signal()));
|
||||
expect(plain.body().tool_choice).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ANTH-006: marks the end of the history and the end of what came before the question for the cache', async () => {
|
||||
const http = fetchAnswering(streamResponse(STREAM));
|
||||
await run(new AnthropicMessagesClient('m', 'k', http.fetcher).stream(REQUEST, signal()));
|
||||
@@ -458,6 +475,17 @@ describe('OpenAiChatClient', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('OACH-009: tool_choice is auto unless the request asks for text only (#3016)', async () => {
|
||||
const client = (fetcher: AiFetch) =>
|
||||
new OpenAiChatClient('openai', 'gpt-5-mini', 'https://api.openai.com/v1', 'sk-key', fetcher);
|
||||
const auto = fetchAnswering(streamResponse(STREAM));
|
||||
await run(client(auto.fetcher).stream(REQUEST, signal()));
|
||||
expect(auto.body().tool_choice).toBe('auto');
|
||||
const none = fetchAnswering(streamResponse(STREAM));
|
||||
await run(client(none.fetcher).stream({ ...REQUEST, toolChoice: 'none' }, signal()));
|
||||
expect(none.body().tool_choice).toBe('none');
|
||||
});
|
||||
|
||||
it('OACH-002: streams the text and assembles the tool call by its index', async () => {
|
||||
const events = await run(
|
||||
new OpenAiChatClient('openai', 'm', 'https://x', 'k', fetchAnswering(streamResponse(STREAM)).fetcher).stream(
|
||||
@@ -648,6 +676,76 @@ describe('OpenAiChatClient', () => {
|
||||
expect(await parameters('http://ollama:11434/v1')).toEqual(toProviderSchema(TOOL.parameters, 'custom'));
|
||||
expect(await parameters('not a url')).toEqual(toProviderSchema(TOOL.parameters, 'custom'));
|
||||
});
|
||||
|
||||
// Azure AI Foundry's answer for a reasoning deployment asked for function tools on Chat Completions (#3043).
|
||||
const REASONING_REFUSAL = {
|
||||
error: {
|
||||
message:
|
||||
"Function tools with reasoning_effort are not supported for gpt-6-luna in /v1/chat/completions. To use function tools, use /v1/responses or set reasoning_effort to 'none'.",
|
||||
type: 'invalid_request_error',
|
||||
param: 'reasoning_effort',
|
||||
code: null,
|
||||
},
|
||||
};
|
||||
const AZURE = 'https://res.services.ai.azure.com/openai/v1';
|
||||
|
||||
it('OACH-010: a server that takes tools only without reasoning is asked again with reasoning_effort none (#3043)', async () => {
|
||||
logWarn.mockClear();
|
||||
const http = fetchAnswering(
|
||||
jsonResponse(400, REASONING_REFUSAL),
|
||||
streamResponse(STREAM),
|
||||
streamResponse(STREAM),
|
||||
streamResponse([{ choices: [{ delta: { content: 'hi' }, finish_reason: 'stop' }] }]),
|
||||
);
|
||||
const client = new OpenAiChatClient('custom', 'gpt-6-luna', AZURE, 'k', http.fetcher);
|
||||
|
||||
const events = await run(client.stream(REQUEST, signal()));
|
||||
// Nothing of the refused request reaches the turn: it answers as if the first request had been taken.
|
||||
expect(events.filter((event) => event.type === 'tool-call')).toHaveLength(1);
|
||||
expect(events.at(-1)).toEqual({ type: 'finish', reason: 'tool-calls' });
|
||||
expect(http.body(0)).not.toHaveProperty('reasoning_effort');
|
||||
expect(http.body(1)).toMatchObject({ reasoning_effort: 'none', tool_choice: 'auto' });
|
||||
expect(logWarn).toHaveBeenCalledWith(
|
||||
'[ai] custom takes function tools only without reasoning: asking again with reasoning_effort none',
|
||||
);
|
||||
|
||||
// The turn's next step goes out without reasoning right away; a step without tools may reason again.
|
||||
await run(client.stream(REQUEST, signal()));
|
||||
expect(http.body(2)).toMatchObject({ reasoning_effort: 'none' });
|
||||
await run(client.stream({ ...REQUEST, tools: [] }, signal()));
|
||||
expect(http.body(3)).not.toHaveProperty('reasoning_effort');
|
||||
expect(http.calls).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('OACH-011: any other server, refusal or request keeps the body as it was and is not asked again (#3043)', async () => {
|
||||
// Ollama, LM Studio, vLLM and OpenRouter never see the parameter.
|
||||
await Promise.all(
|
||||
(['custom', 'openrouter', 'openai', 'gemini'] as const).map(async (kind) => {
|
||||
const plain = fetchAnswering(streamResponse(STREAM));
|
||||
await run(
|
||||
new OpenAiChatClient(kind, 'm', 'http://ollama:11434/v1', null, plain.fetcher).stream(REQUEST, signal()),
|
||||
);
|
||||
expect(plain.body()).not.toHaveProperty('reasoning_effort');
|
||||
}),
|
||||
);
|
||||
|
||||
const once = async (request: AiChatRequest, ...responses: Response[]) => {
|
||||
const http = fetchAnswering(...responses);
|
||||
const err = await failure(
|
||||
new OpenAiChatClient('custom', 'm', AZURE, 'k', http.fetcher).stream(request, signal()),
|
||||
);
|
||||
return { err, calls: http.calls.length };
|
||||
};
|
||||
// A refusal of another field, of the same field with another status, or of a request without tools.
|
||||
const other = { error: { ...REASONING_REFUSAL.error, param: 'tools[0]' } };
|
||||
expect(await once(REQUEST, jsonResponse(400, other))).toMatchObject({ err: { code: 'generic' }, calls: 1 });
|
||||
expect(await once(REQUEST, jsonResponse(422, REASONING_REFUSAL))).toMatchObject({ calls: 1 });
|
||||
expect(await once({ ...REQUEST, tools: [] }, jsonResponse(400, REASONING_REFUSAL))).toMatchObject({ calls: 1 });
|
||||
// A server that refuses `none` as well is asked only once more, and its refusal is the turn's error.
|
||||
expect(
|
||||
await once(REQUEST, jsonResponse(400, REASONING_REFUSAL), jsonResponse(400, REASONING_REFUSAL)),
|
||||
).toMatchObject({ err: { code: 'generic', status: 400 }, calls: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('OpenAiResponsesClient', () => {
|
||||
@@ -689,6 +787,20 @@ describe('OpenAiResponsesClient', () => {
|
||||
expect(dig(body, 'input', 0)).toEqual({ type: 'message', role: 'developer', content: 'Trip: Japan, 3 days' });
|
||||
});
|
||||
|
||||
it('OARS-006: tool_choice is auto unless the request asks for text only (#3016)', async () => {
|
||||
const auto = fetchAnswering(streamResponse(STREAM));
|
||||
await run(new OpenAiResponsesClient('gpt-6.1-sol', tokens('at-1'), auto.fetcher).stream(REQUEST, signal()));
|
||||
expect(auto.body().tool_choice).toBe('auto');
|
||||
const none = fetchAnswering(streamResponse(STREAM));
|
||||
await run(
|
||||
new OpenAiResponsesClient('gpt-6.1-sol', tokens('at-1'), none.fetcher).stream(
|
||||
{ ...REQUEST, toolChoice: 'none' },
|
||||
signal(),
|
||||
),
|
||||
);
|
||||
expect(none.body().tool_choice).toBe('none');
|
||||
});
|
||||
|
||||
it('OARS-002: streams text, yields the call, then usage, the items to replay and the finish', async () => {
|
||||
const events = await run(
|
||||
new OpenAiResponsesClient('m', tokens('at'), fetchAnswering(streamResponse(STREAM)).fetcher).stream(
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { UserAirtrailRepository } from '../../../src/db/repositories/UserAirtrail.repository';
|
||||
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
|
||||
import { AirtrailService } from '../../../src/nest/integrations/airtrail.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
@@ -42,9 +43,14 @@ const listFlights = vi.fn();
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
usersRepo = t.repo(Users);
|
||||
svc = new AirtrailService(new UserAirtrailRepository(t.orm.em), new AuditService(t.repo(AuditLog), usersRepo), {
|
||||
listFlights,
|
||||
} as unknown as AirtrailClient);
|
||||
svc = new AirtrailService(
|
||||
new UserAirtrailRepository(t.orm.em),
|
||||
new AuditService(t.repo(AuditLog), usersRepo),
|
||||
{
|
||||
listFlights,
|
||||
} as unknown as AirtrailClient,
|
||||
new UnitOfWork(t.orm.em),
|
||||
);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
@@ -89,3 +95,41 @@ describe('AirtrailService — at-rest encryption (3h L3)', () => {
|
||||
expect((await svc.getAirtrailCredentials(user.id))?.apiKey).toBe('second-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AirtrailService — the stored key stays with its host (GHSA-mwf5-5px8-c9h5)', () => {
|
||||
const MASK = '••••••••';
|
||||
|
||||
it.each([
|
||||
['masked', MASK],
|
||||
['blank', ''],
|
||||
['left out', undefined],
|
||||
])('AIRTRAIL-SVC-HOST-001: a new host saved with the key %s drops the stored key', async (_label, keyField) => {
|
||||
const { user } = createUser(testDb);
|
||||
await svc.saveSettings(user.id, 'https://airtrail-a.example.test', 'key-for-a', false, false, null);
|
||||
|
||||
await svc.saveSettings(user.id, 'https://other-host.example.test', keyField, false, false, null);
|
||||
|
||||
expect(await rawAirtrailKey(user.id)).toBeNull();
|
||||
expect(await svc.getAirtrailCredentials(user.id)).toBeNull();
|
||||
expect((await readUser(t, user.id)).airtrail_url).toBe('https://other-host.example.test');
|
||||
});
|
||||
|
||||
it('AIRTRAIL-SVC-HOST-002: a path edit on the same origin keeps the stored key', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await svc.saveSettings(user.id, 'https://airtrail-a.example.test', 'key-for-a', false, false, null);
|
||||
|
||||
await svc.saveSettings(user.id, 'https://airtrail-a.example.test/api', MASK, false, false, null);
|
||||
|
||||
expect((await svc.getAirtrailCredentials(user.id))?.apiKey).toBe('key-for-a');
|
||||
});
|
||||
|
||||
it('AIRTRAIL-SVC-HOST-003: a new host saved with a new key stores that key', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await svc.saveSettings(user.id, 'https://airtrail-a.example.test', 'key-for-a', false, false, null);
|
||||
|
||||
await svc.saveSettings(user.id, 'https://other-host.example.test', 'key-for-b', false, false, null);
|
||||
|
||||
const creds = await svc.getAirtrailCredentials(user.id);
|
||||
expect(creds).toMatchObject({ baseUrl: 'https://other-host.example.test', apiKey: 'key-for-b' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,18 +45,39 @@ describe('the derived key lists', () => {
|
||||
'password_registration',
|
||||
'oidc_login',
|
||||
'oidc_registration',
|
||||
'oidc_auto_redirect',
|
||||
'passkey_login',
|
||||
'webauthn_rp_id',
|
||||
'webauthn_origins',
|
||||
'places_provider',
|
||||
'flight_live_enabled',
|
||||
'mail_ingest_enabled',
|
||||
'mail_ingest_transport',
|
||||
'mail_ingest_imap_host',
|
||||
'mail_ingest_imap_port',
|
||||
'mail_ingest_imap_tls',
|
||||
'mail_ingest_imap_user',
|
||||
'mail_ingest_imap_pass',
|
||||
'mail_ingest_imap_mailbox',
|
||||
'mail_ingest_address_template',
|
||||
'mail_ingest_webhook_secret',
|
||||
'mail_ingest_ai_per_user_daily',
|
||||
]);
|
||||
});
|
||||
|
||||
it('APPSET-002: the masked and the encrypted keys', () => {
|
||||
expect([...MASKED_ADMIN_SETTING_KEYS].sort()).toEqual(['admin_ntfy_token', 'admin_webhook_url', 'smtp_pass']);
|
||||
expect([...MASKED_ADMIN_SETTING_KEYS].sort()).toEqual([
|
||||
'admin_ntfy_token',
|
||||
'admin_webhook_url',
|
||||
'mail_ingest_imap_pass',
|
||||
'mail_ingest_webhook_secret',
|
||||
'smtp_pass',
|
||||
]);
|
||||
expect([...ENCRYPTED_APP_SETTING_KEYS].sort()).toEqual([
|
||||
'admin_ntfy_token',
|
||||
'admin_webhook_url',
|
||||
'mail_ingest_imap_pass',
|
||||
'mail_ingest_webhook_secret',
|
||||
'oidc_client_secret',
|
||||
'service_key',
|
||||
'smtp_pass',
|
||||
@@ -82,6 +103,7 @@ describe('the derived key lists', () => {
|
||||
'places_details_enabled',
|
||||
'places_enrich_enabled',
|
||||
'place_shadow_enabled',
|
||||
'oidc_auto_redirect',
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
@@ -131,6 +153,7 @@ describe('reading', () => {
|
||||
oidc_client_secret: ['OIDC_CLIENT_SECRET', 'oidc-env-secret'],
|
||||
oidc_display_name: ['OIDC_DISPLAY_NAME', 'Company SSO'],
|
||||
oidc_discovery_url: ['OIDC_DISCOVERY_URL', 'https://idp.env.example/.well-known/openid-configuration'],
|
||||
flight_live_enabled: ['FLIGHT_LIVE_ENABLED', 'false'],
|
||||
};
|
||||
const withEnv = (Object.entries(APP_SETTINGS) as Array<[string, AppSettingDef]>)
|
||||
.filter(([, def]) => def.env)
|
||||
|
||||
@@ -109,6 +109,7 @@ beforeAll(async () => {
|
||||
await createTestJourneyPhotosRepo(testDb),
|
||||
await createTestJourneyEntryPhotosRepo(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
{ releaseValues: async () => 0 } as never, // StorageReleaseService
|
||||
),
|
||||
await createTestUnitOfWork(testDb),
|
||||
await createTestDayAssignmentsRepo(testDb),
|
||||
|
||||
@@ -65,6 +65,7 @@ const KINDS: Record<string, AssistantToolKind> = {
|
||||
get_weather: 'read',
|
||||
get_place_details: 'read',
|
||||
create_place: 'write',
|
||||
open_trip_chat: 'read',
|
||||
};
|
||||
|
||||
/** What the fake tools answer, per tool; anything else fails. */
|
||||
@@ -75,6 +76,7 @@ const ANSWERS: Record<string, unknown> = {
|
||||
},
|
||||
get_weather: { weather: { temp: 20, main: 'Clouds', description: 'cloudy', type: 'climate' } },
|
||||
get_place_details: { details: { name: 'Ginkaku-ji' } },
|
||||
open_trip_chat: { offered: true },
|
||||
};
|
||||
|
||||
function fakeTools() {
|
||||
@@ -345,6 +347,55 @@ describe('runAgentLoop', () => {
|
||||
expect(assistant.toolCalls[0].id).toBe('call_id-1');
|
||||
});
|
||||
|
||||
it('ASTAGT-006b: a renamed call keeps its thought signature and its record, for the next step and the stored row (#3094)', async () => {
|
||||
const t = setup([
|
||||
[
|
||||
{ type: 'tool-call', call: { id: 'call_0', name: 'list_places', args: {} } },
|
||||
{
|
||||
type: 'provider-state',
|
||||
state: { adapter: 'openai-chat', model: 'gemini-3-flash', signatures: { call_0: 'sig-A' } },
|
||||
},
|
||||
{ type: 'finish', reason: 'tool-calls' },
|
||||
],
|
||||
[{ type: 'text-delta', delta: 'Found it' }],
|
||||
]);
|
||||
t.input.usedCallIds.add('call_0');
|
||||
await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
const renamed = { adapter: 'openai-chat', model: 'gemini-3-flash', signatures: { 'call_id-1': 'sig-A' } };
|
||||
expect(t.requests[1].messages[1]).toMatchObject({
|
||||
role: 'assistant',
|
||||
toolCalls: [{ id: 'call_id-1' }],
|
||||
providerState: renamed,
|
||||
});
|
||||
expect(t.memory.saved[0].step.providerState).toEqual(renamed);
|
||||
|
||||
const anthropic = setup([
|
||||
[
|
||||
{ type: 'tool-call', call: { id: 'toolu_1', name: 'list_places', args: {} } },
|
||||
{
|
||||
type: 'provider-state',
|
||||
state: {
|
||||
adapter: 'anthropic-messages',
|
||||
blocks: [
|
||||
{ type: 'thinking', thinking: 'look', signature: 's' },
|
||||
{ type: 'tool_use', id: 'toolu_1', name: 'list_places', input: {} },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[{ type: 'text-delta', delta: 'Found it' }],
|
||||
]);
|
||||
anthropic.input.usedCallIds.add('toolu_1');
|
||||
await runAgentLoop(anthropic.deps, anthropic.input, anthropic.writer, new AbortController().signal);
|
||||
expect(anthropic.memory.saved[0].step.providerState).toEqual({
|
||||
adapter: 'anthropic-messages',
|
||||
blocks: [
|
||||
{ type: 'thinking', thinking: 'look', signature: 's' },
|
||||
{ type: 'tool_use', id: 'call_id-1', name: 'list_places', input: {} },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTAGT-007: stops after MAX_STEPS steps with max_steps', async () => {
|
||||
const reads = Array.from({ length: MAX_STEPS }, (_, i): Step => [
|
||||
{ type: 'tool-call', call: { id: `r${i}`, name: 'list_places', args: {} } },
|
||||
@@ -830,6 +881,10 @@ describe('runAgentLoop', () => {
|
||||
]);
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('stop');
|
||||
// Only the step after the ask may not call a tool: a model offering follow-ups again has to write (#3016).
|
||||
expect(t.requests[0].toolChoice).toBeUndefined();
|
||||
expect(t.requests[1].toolChoice).toBe('none');
|
||||
expect(t.requests[1].tools.length).toBeGreaterThan(0);
|
||||
const second = t.requests[1].messages;
|
||||
expect(second.at(-2)).toEqual({
|
||||
role: 'assistant',
|
||||
@@ -859,6 +914,79 @@ describe('runAgentLoop', () => {
|
||||
expect(outcome).toMatchObject({ end: 'failed', code: 'empty_answer' });
|
||||
expect(t.requests).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('ASTAGT-047: the text-only request starts with the step after the ask, never before it (#3016)', async () => {
|
||||
const t = setup([
|
||||
[{ type: 'tool-call', call: { id: 'l1', name: 'list_places', args: {} } }],
|
||||
[ask('toolu_9', ['More stops']), { type: 'finish', reason: 'tool-calls' }],
|
||||
[
|
||||
{ type: 'text-delta', delta: 'Two stops so far.' },
|
||||
{ type: 'finish', reason: 'stop' },
|
||||
],
|
||||
]);
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('stop');
|
||||
expect(t.requests.map((request) => request.toolChoice)).toEqual([undefined, undefined, 'none']);
|
||||
});
|
||||
|
||||
it('ASTAGT-050: an empty step after the ask gets a push that is text-only too, so offered follow-ups cannot hide the answer again', async () => {
|
||||
const t = setup([
|
||||
[ask('toolu_10', ['Stops on the drive']), { type: 'finish', reason: 'tool-calls' }],
|
||||
[{ type: 'finish', reason: 'stop' }],
|
||||
[
|
||||
{ type: 'text-delta', delta: 'You leave Lisbon on day 4.' },
|
||||
{ type: 'finish', reason: 'stop' },
|
||||
],
|
||||
]);
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('stop');
|
||||
expect(t.requests.map((request) => request.toolChoice)).toEqual([undefined, 'none', 'none']);
|
||||
expect(t.requests[2].messages.at(-1)).toMatchObject({ role: 'user', text: expect.stringContaining('as text') });
|
||||
expect(t.chunks).toContainEqual({ type: 'data-trek-follow-ups', data: { questions: ['Stops on the drive'] } });
|
||||
});
|
||||
|
||||
it('ASTAGT-045: follow-ups with no answer after an announcing first answer are still asked for the answer', async () => {
|
||||
const t = setup([
|
||||
[{ type: 'text-delta', delta: 'Let me check your places:' }],
|
||||
[{ type: 'tool-call', call: { id: 'l1', name: 'list_places', args: {} } }],
|
||||
[ask('toolu_8', ['Add Ginkaku-ji']), { type: 'finish', reason: 'tool-calls' }],
|
||||
[{ type: 'text-delta', delta: 'Kinkaku-ji is the only place so far.' }],
|
||||
]);
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('stop');
|
||||
expect(t.requests).toHaveLength(4);
|
||||
expect(t.requests[1].messages.at(-1)).toMatchObject({ role: 'user', text: expect.stringContaining('now') });
|
||||
expect(t.requests[3].messages.at(-1)).toMatchObject({
|
||||
role: 'tool',
|
||||
toolCallId: 'toolu_8',
|
||||
output: expect.stringContaining('Not shown yet'),
|
||||
});
|
||||
expect(t.chunks).toContainEqual({ type: 'data-trek-follow-ups', data: { questions: ['Add Ginkaku-ji'] } });
|
||||
expect(t.memory.saved.map((saved) => saved.status)).not.toContain('error');
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTAGT-046: a change its session sends back (called before its tools were loaded) is a tool error, never held (#2967)', async () => {
|
||||
const t = setup([
|
||||
[{ type: 'tool-call', call: { id: 'w1', name: 'create_place', args: { name: 'Blind' } } }],
|
||||
[{ type: 'tool-call', call: { id: 'w2', name: 'create_place', args: { name: 'With schema' } } }],
|
||||
]);
|
||||
t.tools.pinArgs.mockImplementationOnce(() => ({ error: 'create_place did not run: send it again' }));
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('awaiting');
|
||||
expect(t.memory.saved[0].step.parts).toContainEqual({
|
||||
type: 'tool-call',
|
||||
toolCallId: 'w1',
|
||||
toolName: 'create_place',
|
||||
args: { name: 'Blind' },
|
||||
result: 'create_place did not run: send it again',
|
||||
isError: true,
|
||||
});
|
||||
const sentBack = t.requests[1].messages.find((m) => m.role === 'tool' && m.toolCallId === 'w1');
|
||||
expect(sentBack).toMatchObject({ isError: true, output: expect.stringContaining('did not run') });
|
||||
expect(t.deps.describe).toHaveBeenCalledTimes(1);
|
||||
expect(t.memory.held).toHaveLength(1);
|
||||
expect(t.memory.held[0].held.map((call) => call.args)).toEqual([{ name: 'With schema' }]);
|
||||
});
|
||||
|
||||
it('ASTAGT-038: followUpsOf trims, drops duplicates and blanks, cuts each to a chip and keeps three', () => {
|
||||
@@ -961,4 +1089,54 @@ describe('runAgentLoop', () => {
|
||||
expect(JSON.stringify(t.chunks)).not.toContain('HM4X2');
|
||||
expect(JSON.stringify(t.memory.saved)).not.toContain('HM4X2');
|
||||
});
|
||||
|
||||
it('ASTAGT-048: an answer that hands the talk on to a trip chat ends the turn; the model is not asked to answer twice', async () => {
|
||||
const t = setup([
|
||||
[
|
||||
{ type: 'text-delta', delta: 'Your next trip is Florida.' },
|
||||
{
|
||||
type: 'tool-call',
|
||||
call: { id: 'toolu_h', name: 'open_trip_chat', args: { tripId: 1, question: 'Book the Uber' } },
|
||||
},
|
||||
{ type: 'finish', reason: 'tool-calls' },
|
||||
],
|
||||
[{ type: 'text-delta', delta: 'Your next trip is Florida.' }],
|
||||
]);
|
||||
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(outcome.end).toBe('stop');
|
||||
expect(t.requests).toHaveLength(1);
|
||||
expect(t.tools.call).toHaveBeenCalledTimes(1);
|
||||
expect(t.memory.saved).toHaveLength(1);
|
||||
expect(t.memory.saved[0].step.parts.map((part) => part.type)).toEqual(['text', 'tool-call']);
|
||||
});
|
||||
|
||||
it('ASTAGT-049: a hand-on without any answer, or beside a read, still asks the model again', async () => {
|
||||
const alone = setup([
|
||||
[
|
||||
{
|
||||
type: 'tool-call',
|
||||
call: { id: 'toolu_h', name: 'open_trip_chat', args: { tripId: 1, question: 'Book it' } },
|
||||
},
|
||||
{ type: 'finish', reason: 'tool-calls' },
|
||||
],
|
||||
[{ type: 'text-delta', delta: 'Go on in the trip chat.' }],
|
||||
]);
|
||||
await runAgentLoop(alone.deps, alone.input, alone.writer, new AbortController().signal);
|
||||
expect(alone.requests).toHaveLength(2);
|
||||
|
||||
const withRead = setup([
|
||||
[
|
||||
{ type: 'text-delta', delta: 'Let me look.' },
|
||||
{ type: 'tool-call', call: { id: 'toolu_r', name: 'list_places', args: { tripId: 1 } } },
|
||||
{
|
||||
type: 'tool-call',
|
||||
call: { id: 'toolu_h', name: 'open_trip_chat', args: { tripId: 1, question: 'Book it' } },
|
||||
},
|
||||
{ type: 'finish', reason: 'tool-calls' },
|
||||
],
|
||||
[{ type: 'text-delta', delta: 'Kinkaku-ji is on the list.' }],
|
||||
]);
|
||||
await runAgentLoop(withRead.deps, withRead.input, withRead.writer, new AbortController().signal);
|
||||
expect(withRead.requests).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { McpToolGuardsService } from '../../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../../../../src/nest/trip-membership/trip-access.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
import type { BookingImportPreviewItem, LlmParseOutcome } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -48,7 +48,10 @@ async function make(opts: Opts = {}) {
|
||||
items: Array.from({ length: MAX_WRITES_PER_STEP + 2 }, (_, index) => ({ ...ITEM, title: `Leg ${index}` })),
|
||||
warnings: [],
|
||||
})),
|
||||
confirm: vi.fn(async () => ({ created: [{ id: 81, title: 'ICE 123', type: 'train', day_id: 31 }] })),
|
||||
confirm: vi.fn(async (): Promise<{ created: unknown[]; failed: { index: number; reason: string }[] }> => ({
|
||||
created: [{ id: 81, title: 'ICE 123', type: 'train', day_id: 31 }],
|
||||
failed: [],
|
||||
})),
|
||||
};
|
||||
const trips = { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 5, user_id: 7 })) };
|
||||
const guards = { hasTripPermission: vi.fn(async () => opts.right !== false) };
|
||||
@@ -110,15 +113,21 @@ describe('AssistantBookingImportService', () => {
|
||||
expect(read.found).toEqual({ bookings: expect.any(Array) });
|
||||
});
|
||||
|
||||
it('ASTBKI-006: reads the reason from the warnings of the preview, for each way it comes back empty', () => {
|
||||
const preview = (...warnings: string[]) => ({ items: [], warnings });
|
||||
expect(emptyReason(preview('a.pdf: no reservations found'), false)).toBe('ai_not_configured');
|
||||
const scan = preview('a.pdf: no readable text found (a scanned PDF needs a model that reads images)');
|
||||
expect(emptyReason(scan, true)).toBe('no_text');
|
||||
expect(emptyReason(preview('a.pdf: AI parsing failed — 401'), true)).toBe('ai_failed');
|
||||
expect(emptyReason(preview('a.pdf: could not read file — bad xref'), true)).toBe('ai_failed');
|
||||
expect(emptyReason(preview('a.jpg: the configured model does not read images'), true)).toBe('ai_failed');
|
||||
expect(emptyReason(preview('a.pdf: no reservations found'), true)).toBe('nothing_found');
|
||||
it('ASTBKI-006: reads the reason from the outcome of the AI reading, for each way it comes back empty', () => {
|
||||
const preview = (outcome?: LlmParseOutcome) => ({
|
||||
items: [],
|
||||
warnings: ['a.pdf: some text the reason is no longer read from'],
|
||||
files: [{ fileName: 'a.pdf', aiAvailable: true, aiUsed: outcome !== undefined, ...(outcome && { outcome }) }],
|
||||
});
|
||||
expect(emptyReason(preview('provider_error'), false)).toBe('ai_not_configured');
|
||||
expect(emptyReason(preview('no_text'), true)).toBe('no_text');
|
||||
for (const failed of ['provider_error', 'quota_exhausted', 'too_large', 'ai_disabled', 'user_cap'] as const) {
|
||||
expect(emptyReason(preview(failed), true)).toBe('ai_failed');
|
||||
}
|
||||
expect(emptyReason(preview('empty'), true)).toBe('nothing_found');
|
||||
// The extractor read it alone: no AI outcome, nothing found.
|
||||
expect(emptyReason(preview(), true)).toBe('nothing_found');
|
||||
expect(emptyReason({ items: [], warnings: [] }, true)).toBe('nothing_found');
|
||||
});
|
||||
|
||||
it('ASTBKI-003: an applied booking is created through the import, on the trip, without a socket', async () => {
|
||||
@@ -126,7 +135,7 @@ describe('AssistantBookingImportService', () => {
|
||||
const run = await t.service.apply(7, 5, { ...ITEM });
|
||||
const reservation = { id: 81, title: 'ICE 123', type: 'train', day_id: 31 };
|
||||
expect(run).toEqual({ ok: true, value: { reservation } });
|
||||
expect(t.bookingImport.confirm).toHaveBeenCalledWith('5', [ITEM], undefined);
|
||||
expect(t.bookingImport.confirm).toHaveBeenCalledWith('5', 7, [ITEM], undefined);
|
||||
expect(t.trips.findAccessible).toHaveBeenCalledWith(5, 7);
|
||||
expect(t.guards.hasTripPermission).toHaveBeenCalledWith('reservation_edit', 5, 7);
|
||||
});
|
||||
@@ -147,8 +156,14 @@ describe('AssistantBookingImportService', () => {
|
||||
value: 'This booking can no longer be read.',
|
||||
});
|
||||
const none = await make();
|
||||
none.bookingImport.confirm.mockResolvedValueOnce({ created: [] });
|
||||
none.bookingImport.confirm.mockResolvedValueOnce({ created: [], failed: [{ index: 0, reason: 'write_failed' }] });
|
||||
const notAdded = await none.service.apply(7, 5, { ...ITEM });
|
||||
expect(notAdded).toEqual({ ok: false, value: 'The booking could not be added.' });
|
||||
// A booking an earlier import already wrote is named as such, not as a failure.
|
||||
none.bookingImport.confirm.mockResolvedValueOnce({ created: [], failed: [{ index: 0, reason: 'duplicate' }] });
|
||||
expect(await none.service.apply(7, 5, { ...ITEM })).toEqual({
|
||||
ok: false,
|
||||
value: 'This booking is already in the trip.',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
toChatHistory,
|
||||
toThreadMessages,
|
||||
} from '../../../../src/nest/assistant/assistant-history';
|
||||
import type { AssistantMessagePart, AssistantToolApproval } from '@trek/shared';
|
||||
import { ASSISTANT_FOLLOW_UPS_TOOL, type AssistantMessagePart, type AssistantToolApproval } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -651,6 +651,64 @@ describe('toChatHistory: calls the model made of the server tools (#2845)', () =
|
||||
expect(outputs).toEqual(['call_1', 'call_2']);
|
||||
});
|
||||
|
||||
it('ASTHIS-021: a stopped step replayed on another provider names every call it answers', () => {
|
||||
const anthropic = stoppedMidStep({
|
||||
adapter: 'anthropic-messages',
|
||||
blocks: [
|
||||
{ type: 'text', text: 'Let me look.' },
|
||||
{ type: 'tool_use', id: 'call_1', name: 'list_places', input: {} },
|
||||
{ type: 'tool_use', id: 'call_2', name: 'get_weather', input: { day: 3 } },
|
||||
],
|
||||
});
|
||||
expect(anthropic.find((message) => message.role === 'assistant')).toMatchObject({
|
||||
toolCalls: [
|
||||
{ id: 'call_1', name: 'list_places', args: {} },
|
||||
{ id: 'call_2', name: 'get_weather', args: { day: 3 } },
|
||||
],
|
||||
});
|
||||
|
||||
// Chat Completions: every tool message follows an assistant message whose tool_calls name it.
|
||||
const chat = toChatMessages({ system: '', messages: anthropic, tools: [] });
|
||||
chat.forEach((message, index) => {
|
||||
if (message.role !== 'tool') return;
|
||||
const before = chat
|
||||
.slice(0, index)
|
||||
.reverse()
|
||||
.find((earlier) => earlier.role === 'assistant');
|
||||
const named = ((before?.tool_calls ?? []) as Array<{ id: string }>).map((call) => call.id);
|
||||
expect(named).toContain(message.tool_call_id);
|
||||
});
|
||||
|
||||
// Responses: every function_call_output has its function_call before it.
|
||||
const items = toResponsesInput({ system: '', messages: anthropic, tools: [] });
|
||||
items.forEach((item, index) => {
|
||||
if (item.type !== 'function_call_output') return;
|
||||
const made = items
|
||||
.slice(0, index)
|
||||
.some((earlier) => earlier.type === 'function_call' && earlier.call_id === item.call_id);
|
||||
expect(made).toBe(true);
|
||||
});
|
||||
|
||||
// Anthropic: a step the Responses API recorded is rebuilt with every tool_use its results answer.
|
||||
const responses = stoppedMidStep({
|
||||
adapter: 'openai-responses',
|
||||
items: [
|
||||
{ type: 'function_call', call_id: 'call_1', name: 'list_places', arguments: '{}' },
|
||||
{ type: 'function_call', call_id: 'call_2', name: 'get_weather', arguments: 'not json' },
|
||||
],
|
||||
});
|
||||
const messages = toAnthropicMessages(responses);
|
||||
const uses = messages[1].content.filter((block) => block.type === 'tool_use');
|
||||
expect(uses.map((block) => [block.id, block.input])).toEqual([
|
||||
['call_1', {}],
|
||||
['call_2', {}],
|
||||
]);
|
||||
const results = messages[2].content
|
||||
.filter((block) => block.type === 'tool_result')
|
||||
.map((block) => block.tool_use_id);
|
||||
expect(results).toEqual(['call_1', 'call_2']);
|
||||
});
|
||||
|
||||
it('ASTHIS-017: a step that only kept a note is the model call it was, answered with what was kept', () => {
|
||||
const history = toChatHistory(
|
||||
[
|
||||
@@ -682,6 +740,68 @@ describe('toChatHistory: calls the model made of the server tools (#2845)', () =
|
||||
});
|
||||
});
|
||||
|
||||
describe('toChatHistory: the next message after an answer (#3094)', () => {
|
||||
/**
|
||||
* The first answer of #3094 as its rows hold it: a step that only announced
|
||||
* its lookups (the turn pushed it on, and the push is not stored), the
|
||||
* lookups, a step that came back blank with only its follow-ups (asked
|
||||
* again for the answer), and the answer. Then the user writes again.
|
||||
*/
|
||||
function secondMessage(): AiChatMessage[] {
|
||||
return toChatHistory(
|
||||
[
|
||||
row('user', [{ type: 'text', text: 'Hello' }]),
|
||||
row('assistant', [{ type: 'text', text: 'Let me look at your trip:' }]),
|
||||
row('assistant', [
|
||||
{ type: 'tool-call', toolCallId: 'call_a', toolName: 'get_trip_summary', args: {}, result: { days: [] } },
|
||||
{ type: 'tool-call', toolCallId: 'call_b', toolName: 'list_places', args: {}, result: { places: [] } },
|
||||
]),
|
||||
row('assistant', [
|
||||
{ type: 'text', text: '\n\n' },
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'call_c',
|
||||
toolName: ASSISTANT_FOLLOW_UPS_TOOL,
|
||||
args: { questions: ['What is on day 2?'] },
|
||||
result: 'Write your answer now.',
|
||||
},
|
||||
]),
|
||||
row('assistant', [{ type: 'text', text: 'Your trip has no days yet.' }]),
|
||||
row('user', [{ type: 'text', text: 'Add a day' }]),
|
||||
],
|
||||
new Map(),
|
||||
);
|
||||
}
|
||||
|
||||
it('ASTHIS-022: the second message gives Anthropic every tool_use answered and no blank text block', () => {
|
||||
const messages = toAnthropicMessages(secondMessage());
|
||||
messages.forEach((message, index) => {
|
||||
expect(message.role).toBe(index % 2 === 0 ? 'user' : 'assistant');
|
||||
});
|
||||
expect(messages.at(-1)?.content.at(-1)).toEqual({ type: 'text', text: 'Add a day' });
|
||||
messages.forEach((message, index) => {
|
||||
const ids = message.content.filter((block) => block.type === 'tool_use').map((block) => block.id);
|
||||
if (ids.length === 0) return;
|
||||
const results = messages[index + 1].content
|
||||
.filter((block) => block.type === 'tool_result')
|
||||
.map((block) => block.tool_use_id);
|
||||
expect(results).toEqual(ids);
|
||||
});
|
||||
const texts = messages.flatMap((message) => message.content).filter((block) => block.type === 'text');
|
||||
expect(texts.every((block) => typeof block.text === 'string' && block.text.trim() !== '')).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTHIS-023: the second message never has one model message follow another on Chat Completions', () => {
|
||||
const chat = toChatMessages({ system: 'sys', messages: secondMessage(), tools: [] });
|
||||
chat.forEach((message, index) => {
|
||||
if (message.role !== 'assistant') return;
|
||||
expect(['user', 'tool']).toContain(chat[index - 1]?.role);
|
||||
if (typeof message.content === 'string') expect(message.content.trim()).not.toBe('');
|
||||
});
|
||||
expect(chat.at(-1)).toEqual({ role: 'user', content: 'Add a day' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('toThreadMessages', () => {
|
||||
it('ASTHIS-010: the steps of one answer are one message under the first row id', () => {
|
||||
nextId = 10;
|
||||
|
||||
@@ -425,6 +425,79 @@ describe('an assistant tool session', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTTOOL-025: a change called before its group was loaded is sent back until a step was offered its schema (#2967)', async () => {
|
||||
const { userId, tripId } = await ownerWithTrips();
|
||||
const session = await tools.open(userId, tripId);
|
||||
try {
|
||||
expect(session.specs().map((spec) => spec.name)).not.toContain('insert_tour_stop');
|
||||
// Held as a card, the blind arguments would only fail once the user applies it.
|
||||
expect(session.pinArgs('insert_tour_stop', { placeId: '530' })).toEqual({
|
||||
error: expect.stringContaining('"tours" tools, which were not loaded in this turn, so it did not run'),
|
||||
});
|
||||
// A second change of the same step was written without the schema too.
|
||||
expect(session.pinArgs('create_city_walk', { stations: '[1, 2]' })).toEqual({
|
||||
error: expect.stringContaining('did not run'),
|
||||
});
|
||||
// The next step is offered the schema, and the call goes through.
|
||||
expect(session.specs().map((spec) => spec.name)).toContain('insert_tour_stop');
|
||||
expect(session.pinArgs('insert_tour_stop', { placeId: 530 })).toHaveProperty('args');
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTTOOL-028: a change called before its group was loaded is held as always when its arguments already fit', async () => {
|
||||
const { userId, tripId } = await ownerWithTrips();
|
||||
const session = await tools.open(userId, tripId);
|
||||
try {
|
||||
session.specs();
|
||||
const fits = { placeId: 530, expected_revision: 3, stop: { name: 'Hut', lat: 47.1, lng: 11.2 } };
|
||||
expect(session.pinArgs('insert_tour_stop', fits)).toEqual({ args: fits });
|
||||
// Written as text, the same call is still sent back with the schema loaded.
|
||||
expect(session.pinArgs('create_city_walk', { stations: '[1, 2]' })).toEqual({
|
||||
error: expect.stringContaining('did not run'),
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTTOOL-026: only the blind call itself is told about the schema; a later failure of the same tool is not', async () => {
|
||||
const { userId, tripId } = await ownerWithTrips();
|
||||
const session = await tools.open(userId, tripId);
|
||||
try {
|
||||
session.specs();
|
||||
expect(session.pinArgs('get_tour_plan', { placeId: '530' })).toEqual({ args: { placeId: '530' } });
|
||||
const blind = await session.call('get_tour_plan', { placeId: '530' });
|
||||
expect(String(blind.value)).toContain('"tours" tools were loaded in this turn');
|
||||
// Sent again after the next step's specs: it fails on its own, without the hint.
|
||||
session.specs();
|
||||
expect(session.pinArgs('get_tour_plan', { placeId: 999_999 })).toEqual({ args: { placeId: 999_999 } });
|
||||
const again = await session.call('get_tour_plan', { placeId: 999_999 });
|
||||
expect(again.ok).toBe(false);
|
||||
expect(String(again.value)).not.toContain('were loaded in this turn');
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTTOOL-027: a blind read refused before it ran leaves no hint for a later call of the same tool', async () => {
|
||||
const { userId, tripId } = await ownerWithTrips();
|
||||
const session = await tools.open(userId, tripId);
|
||||
try {
|
||||
session.specs();
|
||||
// Called blind, then refused by the loop before it ran: call() never sees it.
|
||||
expect(session.pinArgs('get_tour_plan', { placeId: '530' })).toHaveProperty('args');
|
||||
session.specs();
|
||||
expect(session.pinArgs('get_tour_plan', { placeId: 999_999 })).toEqual({ args: { placeId: 999_999 } });
|
||||
const run = await session.call('get_tour_plan', { placeId: 999_999 });
|
||||
expect(run.ok).toBe(false);
|
||||
expect(String(run.value)).not.toContain('were loaded in this turn');
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTTOOL-014: an undo session holds its target and nothing else', async () => {
|
||||
const { userId, tripId } = await ownerWithTrips();
|
||||
const session = await tools.open(userId, tripId, new Set(['delete_place']));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* ASTCOL-001 to ASTCOL-012: the cards the collections' reads draw beside the
|
||||
* ASTCOL-001 to ASTCOL-012 and ASTCOL-036: the cards the collections' reads draw beside the
|
||||
* answer, built from the tool's raw answer through the guarded registry, so
|
||||
* every card here also passed the card union and the size cap.
|
||||
*/
|
||||
@@ -30,10 +30,17 @@ describe('collection answer cards', () => {
|
||||
color: '#e11d48',
|
||||
placeCount: 10,
|
||||
memberCount: 1,
|
||||
counts: { idea: 4, want: 1, visited: 5 },
|
||||
counts: { idea: 4, want: 1, visited: 5, revisit: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTCOL-036: a place to revisit is counted under its own status (#2567)', () => {
|
||||
const value = collectionValue();
|
||||
value.places[1] = { ...value.places[1], status: 'revisit' };
|
||||
const shown = places('get_collection', { collectionId: 12 }, value);
|
||||
expect(shown?.list?.counts).toEqual({ idea: 4, want: 1, visited: 4, revisit: 1 });
|
||||
});
|
||||
|
||||
it('ASTCOL-002: eight places are shown and the rest counted, in the order the list keeps them', () => {
|
||||
const shown = places('get_collection', { collectionId: 12 }, collectionValue());
|
||||
expect(shown?.places).toHaveLength(8);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* ASTCOL-020 to ASTCOL-035: the change cards of the collections' writes, as
|
||||
* ASTCOL-020 to ASTCOL-035 and ASTCOL-037: the change cards of the collections' writes, as
|
||||
* describeToolCall writes them (the card through the guarded registry, so it
|
||||
* passed the union), and the lookups they read first.
|
||||
*/
|
||||
@@ -104,6 +104,21 @@ describe('collection change cards', () => {
|
||||
expect(placesOf(removed.card).places[0]?.delta?.removed).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTCOL-037: the provider ids, contact and price fields an update now takes are named once each (#2646)', () => {
|
||||
const items = itemsValue([savedPlace()]);
|
||||
const args = {
|
||||
placeId: 34,
|
||||
website: 'septime-charonne.fr',
|
||||
phone: null,
|
||||
price: 45,
|
||||
currency: 'EUR',
|
||||
google_place_id: 'ChIJseptime',
|
||||
osm_id: 'node/1',
|
||||
};
|
||||
const card = placesOf(preview('update_collection_place', args, { items }).card);
|
||||
expect(card.places[0]?.delta?.fields).toEqual(['website', 'phone', 'price', 'mapEntry']);
|
||||
});
|
||||
|
||||
it('ASTCOL-023: a change of a saved place names its fields, its labels as its own list allows them and the list it moves to', () => {
|
||||
const items = itemsValue([savedPlace()]);
|
||||
// In its own list: the labels asked for replace the ones it carries.
|
||||
@@ -138,7 +153,7 @@ describe('collection change cards', () => {
|
||||
color: null,
|
||||
placeCount: null,
|
||||
memberCount: 0,
|
||||
counts: { idea: 0, want: 0, visited: 0 },
|
||||
counts: { idea: 0, want: 0, visited: 0, revisit: 0 },
|
||||
},
|
||||
removed: false,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getCountryFromCoords } from '../../../src/utils/country-borders';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// A point that no admin0 polygon contains (just off a simplified coastline, or in a data
|
||||
// gap) used to go to the candidate with the smallest bounding box. It now goes to the
|
||||
// candidate whose border is nearest.
|
||||
|
||||
describe('getCountryFromCoords, a point no polygon contains', () => {
|
||||
it('ATLAS-SVC-056: a point just off a simplified coastline goes to the nearest border, not the smallest box', () => {
|
||||
// Central Nice lies about 80 m outside France's simplified coast and 20+ km from Italy,
|
||||
// so no polygon contains it. Both boxes cover it and Italy's is the smaller one, so the
|
||||
// smallest-box fallback put the whole Nice-Menton strip in Italy.
|
||||
expect(getCountryFromCoords(43.6947, 7.2578)).toBe('FR'); // Hôtel Negresco, Nice
|
||||
expect(getCountryFromCoords(43.6969, 7.2703)).toBe('FR'); // Place Masséna, Nice
|
||||
expect(getCountryFromCoords(43.6598, 7.2137)).toBe('FR'); // Nice Côte d'Azur airport
|
||||
expect(getCountryFromCoords(43.7753, 7.5029)).toBe('FR'); // Menton
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-057: the Riviera neighbours stay where they were', () => {
|
||||
expect(getCountryFromCoords(43.7392, 7.428)).toBe('MC'); // Casino de Monte-Carlo
|
||||
expect(getCountryFromCoords(43.7918, 7.6033)).toBe('IT'); // Ventimiglia
|
||||
expect(getCountryFromCoords(43.817, 7.7751)).toBe('IT'); // Sanremo
|
||||
expect(getCountryFromCoords(43.5814, 7.1237)).toBe('FR'); // Antibes
|
||||
});
|
||||
});
|
||||
@@ -114,7 +114,31 @@ function oldLookup(old: ReturnType<typeof oldIndexes>, lat: number, lng: number)
|
||||
}
|
||||
if (oldPointInGeometry(lng, lat, poly)) return code;
|
||||
}
|
||||
return looseBoxFallback ?? candidates[0].code;
|
||||
if (looseBoxFallback !== null) return looseBoxFallback;
|
||||
// Nearest border among the candidates, as country-borders.ts ranks a point no polygon holds.
|
||||
let nearest = candidates[0].code;
|
||||
let nearestDistance = Infinity;
|
||||
const kx = Math.cos((lat * Math.PI) / 180);
|
||||
for (const { code } of candidates) {
|
||||
const poly = old.polys.get(code);
|
||||
if (!poly) continue;
|
||||
for (const ring of poly.rings) {
|
||||
for (let i = 1; i < ring.length / 2; i++) {
|
||||
const ax = (ring[2 * (i - 1)] - lng) * kx;
|
||||
const ay = ring[2 * (i - 1) + 1] - lat;
|
||||
const dx = (ring[2 * i] - lng) * kx - ax;
|
||||
const dy = ring[2 * i + 1] - lat - ay;
|
||||
const len = dx * dx + dy * dy;
|
||||
const t = len > 0 ? Math.min(1, Math.max(0, -(ax * dx + ay * dy) / len)) : 0;
|
||||
const d = (ax + t * dx) ** 2 + (ay + t * dy) ** 2;
|
||||
if (d < nearestDistance) {
|
||||
nearestDistance = d;
|
||||
nearest = code;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
// Deterministic points per country: about `perCountry` vertices spread over all its rings,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getRegionGeoGz, getRegionGeoJson } from '../../../src/nest/atlas/atlas-geo';
|
||||
import { getRegionFromCoords, getRegionGeoGz, getRegionGeoJson } from '../../../src/nest/atlas/atlas-geo';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import zlib from 'zlib';
|
||||
@@ -57,3 +57,33 @@ describe('getRegionGeoGz', () => {
|
||||
expect(await Promise.all(codes.map((code) => getRegionGeoGz(code)))).toEqual(codes.map(() => null));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ireland resolves to its counties (#2922)', () => {
|
||||
// Inland, coastal and near-border places, one county each. The counties come from
|
||||
// Tailte Éireann and are simplified by the builder itself, so a point that lands in no
|
||||
// county or in the wrong one would mean the simplification opened a gap or moved a border.
|
||||
const places: [string, number, number, string][] = [
|
||||
['Dublin, Trinity College', 53.3438, -6.2546, 'IE-D'],
|
||||
['Howth village', 53.3866, -6.07, 'IE-D'],
|
||||
['Cork, St. Patrick Street', 51.8985, -8.4731, 'IE-CO'],
|
||||
['Galway, Eyre Square', 53.2743, -9.0491, 'IE-G'],
|
||||
['Killarney', 52.0599, -9.5044, 'IE-KY'],
|
||||
['Cliffs of Moher visitor centre', 52.9719, -9.4265, 'IE-CE'],
|
||||
['Kilkenny Castle', 52.6503, -7.2492, 'IE-KK'],
|
||||
['Letterkenny', 54.9503, -7.7334, 'IE-DL'],
|
||||
['Westport', 53.8008, -9.5223, 'IE-MO'],
|
||||
['Cashel, Rock of Cashel', 52.5201, -7.8906, 'IE-TA'],
|
||||
];
|
||||
|
||||
it.each(places)('ATLAS-SVC-051: %s lies in its county', async (_name, lat, lng, code) => {
|
||||
expect((await getRegionFromCoords('IE', lat, lng))?.region_code).toBe(code);
|
||||
});
|
||||
|
||||
it('ATLAS-SVC-052: a county comes back under its English name', async () => {
|
||||
expect(await getRegionFromCoords('ie', 53.3438, -6.2546)).toEqual({
|
||||
country_code: 'IE',
|
||||
region_code: 'IE-D',
|
||||
region_name: 'Dublin',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// The dashboard's order of visited countries (#2648).
|
||||
import { CountryVisits, latestPerCoordinate } from '../../../src/nest/atlas/atlas-visit-order';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
describe('CountryVisits', () => {
|
||||
it('ATLAS-ORDER-001: puts the latest reached country first and the hand-marked ones after', () => {
|
||||
const visits = new CountryVisits();
|
||||
visits.note('pt', '2025-04-10');
|
||||
visits.note('JP', '2026-05-02');
|
||||
visits.note('pt', '2026-01-20');
|
||||
visits.note(null, '2026-09-01');
|
||||
expect(visits.ordered(['IS', 'JP'])).toEqual(['JP', 'PT', 'IS']);
|
||||
});
|
||||
|
||||
it('ATLAS-ORDER-002: keeps the order a country of one trip was found in', () => {
|
||||
const visits = new CountryVisits();
|
||||
visits.note('FR', '2026-03-01');
|
||||
visits.note('ES', '2026-03-01');
|
||||
visits.note('IT', null);
|
||||
expect(visits.ordered([])).toEqual(['FR', 'ES', 'IT']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('latestPerCoordinate', () => {
|
||||
it('ATLAS-ORDER-003: keeps one row per coordinate, the one of the latest trip', () => {
|
||||
const rows = [
|
||||
{ id: 1, lat: 1, lng: 2, trip_last_date: '2025-01-01' },
|
||||
{ id: 2, lat: 1, lng: 2, trip_last_date: '2026-01-01' },
|
||||
{ id: 3, lat: 3, lng: 4, trip_last_date: null },
|
||||
];
|
||||
expect(latestPerCoordinate(rows).map((r) => r.id)).toEqual([2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -152,6 +152,26 @@ describe('Atlas admin1 region bundle (#1217)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* geoBoundaries has no county layer for Ireland: its ADM1 is the four provinces and
|
||||
* its ADM2 the 166 local electoral areas, so Ireland showed four provinces next to
|
||||
* a UK of counties (#2922). Ireland's regions come from Tailte Éireann's 26 counties
|
||||
* instead, under their ISO 3166-2:IE codes.
|
||||
*/
|
||||
it('ATLAS-BUNDLE-011 — Ireland ships its 26 counties, not the four provinces (#2922)', () => {
|
||||
const ie = regions('IE') as unknown as { properties: { iso_3166_2: string; name: string; admin: string } }[];
|
||||
const codes = ie.map((f) => f.properties.iso_3166_2).sort();
|
||||
// ISO 3166-2:IE, Dublin, Cork, Galway and Limerick each one county (city and county together).
|
||||
const iso =
|
||||
'IE-CE IE-CN IE-CO IE-CW IE-D IE-DL IE-G IE-KE IE-KK IE-KY IE-LD IE-LH IE-LK ' +
|
||||
'IE-LM IE-LS IE-MH IE-MN IE-MO IE-OY IE-RN IE-SO IE-TA IE-WD IE-WH IE-WW IE-WX';
|
||||
expect(codes).toEqual(iso.split(' '));
|
||||
const byCode = new Map(ie.map((f) => [f.properties.iso_3166_2, f.properties]));
|
||||
expect(byCode.get('IE-D')?.name).toBe('Dublin');
|
||||
expect(byCode.get('IE-TA')?.name).toBe('Tipperary');
|
||||
expect(new Set(ie.map((f) => f.properties.admin))).toEqual(new Set(['Ireland']));
|
||||
});
|
||||
|
||||
it('ATLAS-BUNDLE-006 — China ships Guangdong Province, not Guangzhou Province', () => {
|
||||
const cn = (
|
||||
features as unknown as { properties: { iso_a2: string | null; name?: string; iso_3166_2: string } }[]
|
||||
|
||||
@@ -21,6 +21,7 @@ import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service'
|
||||
import { WebauthnConfigService } from '../../../src/nest/auth/webauthn-config.service';
|
||||
import { BudgetService } from '../../../src/nest/budget/budget.service';
|
||||
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
|
||||
import { encrypt_api_key } from '../../../src/nest/common/crypto/apiKeyCrypto';
|
||||
import { AllowedFileTypesService } from '../../../src/nest/files/allowed-file-types.service';
|
||||
import { DEFAULT_ALLOWED_EXTENSIONS } from '../../../src/nest/files/files.constants';
|
||||
import { MailerService } from '../../../src/nest/notifications/mailer/mailer.service';
|
||||
@@ -815,6 +816,15 @@ describe('getAppConfig', () => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('AUTH-DB-052d: oidc_auto_redirect stays on until an admin stores false (#2925)', async () => {
|
||||
createUser(testDb);
|
||||
expect((await svc.getAppConfig(null)).oidc_auto_redirect).toBe(true);
|
||||
await appSetting('oidc_auto_redirect', 'false');
|
||||
expect((await svc.getAppConfig(null)).oidc_auto_redirect).toBe(false);
|
||||
await appSetting('oidc_auto_redirect', 'true');
|
||||
expect((await svc.getAppConfig(null)).oidc_auto_redirect).toBe(true);
|
||||
});
|
||||
|
||||
it('AUTH-DB-052b: managed is false unless the install says otherwise', async () => {
|
||||
createUser(testDb);
|
||||
expect((await svc.getAppConfig(null)).managed).toBe(false);
|
||||
@@ -1054,6 +1064,23 @@ describe('deleteAccount', () => {
|
||||
});
|
||||
|
||||
describe('updateAppSettings', () => {
|
||||
it('AUTH-DB-070b: FLIGHT_LIVE_ENABLED holds the switch: the form shows it as env_override_*, a save skips it', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
vi.stubEnv('FLIGHT_LIVE_ENABLED', 'false');
|
||||
try {
|
||||
await appSetting('flight_live_enabled', 'true');
|
||||
const read = await asLegacyResult(svc.getAppSettings(user.id));
|
||||
expect(read.data).toMatchObject({ flight_live_enabled: 'false', env_override_flight_live_enabled: 'false' });
|
||||
|
||||
await deleteRows(orm, AppSettings, { key: 'flight_live_enabled' });
|
||||
const saved = await asLegacyResult(svc.updateAppSettings(user.id, { flight_live_enabled: 'true' }));
|
||||
expect(saved).toMatchObject({ success: true, managedKeys: ['flight_live_enabled'] });
|
||||
expect(await findRow(orm, AppSettings, { key: 'flight_live_enabled' })).toBeNull();
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('AUTH-DB-071: 403 for non-admin', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
expect((await asLegacyResult(svc.updateAppSettings(user.id, {}))).status).toBe(403);
|
||||
@@ -1100,6 +1127,41 @@ describe('updateAppSettings', () => {
|
||||
expect(result.auditDebugDetails).not.toHaveProperty('smtp_pass', 'stored');
|
||||
await deleteRows(orm, AppSettings, { key: { $in: ['smtp_pass', 'notification_channels'] } });
|
||||
});
|
||||
|
||||
const HOOK_SECRET = 'h'.repeat(40);
|
||||
|
||||
it('AUTH-DB-075b: the mail import secrets are stored encrypted and never reach the audit row', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const result = await asLegacyResult(
|
||||
svc.updateAppSettings(user.id, {
|
||||
mail_ingest_imap_host: 'imap.example.com',
|
||||
mail_ingest_imap_pass: 'box-secret',
|
||||
mail_ingest_webhook_secret: HOOK_SECRET,
|
||||
}),
|
||||
);
|
||||
expect(result.success).toBe(true);
|
||||
expect(vi.mocked(encrypt_api_key)).toHaveBeenCalledWith('box-secret');
|
||||
expect(vi.mocked(encrypt_api_key)).toHaveBeenCalledWith(HOOK_SECRET);
|
||||
expect(result.auditDebugDetails).toEqual({
|
||||
mail_ingest_imap_host: 'imap.example.com',
|
||||
mail_ingest_imap_pass: '***',
|
||||
mail_ingest_webhook_secret: '***',
|
||||
});
|
||||
expect(result.auditSummary).toMatchObject({ mail_ingest_settings_updated: true });
|
||||
const keys = ['mail_ingest_imap_host', 'mail_ingest_imap_pass', 'mail_ingest_webhook_secret'];
|
||||
await deleteRows(orm, AppSettings, { key: { $in: keys } });
|
||||
});
|
||||
|
||||
it('AUTH-DB-075c: a webhook secret shorter than 32 characters is refused, and nothing of the form lands', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
await expect(
|
||||
svc.updateAppSettings(user.id, { mail_ingest_imap_host: 'imap.example.com', mail_ingest_webhook_secret: 'abc' }),
|
||||
).rejects.toThrow('The webhook secret needs at least 32 characters');
|
||||
expect(await readAppSetting(orm, 'mail_ingest_imap_host')).toBeNull();
|
||||
const cleared = await asLegacyResult(svc.updateAppSettings(user.id, { mail_ingest_webhook_secret: '' }));
|
||||
expect(cleared.success).toBe(true);
|
||||
await deleteRows(orm, AppSettings, { key: 'mail_ingest_webhook_secret' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('MFA success flows', () => {
|
||||
|
||||
@@ -15,7 +15,35 @@ vi.mock('../../../../src/db/database', () => ({
|
||||
isOwner: () => false,
|
||||
getPlaceWithTags: () => null,
|
||||
}));
|
||||
const permissionsStub = { checkPermission: vi.fn(() => true) };
|
||||
const guardsStub = { hasTripPermission: vi.fn(async () => true) };
|
||||
|
||||
/** The service under test with the named collaborators given, every other one left out. */
|
||||
function buildService(deps: Partial<Record<(typeof DEP_ORDER)[number], unknown>>): BookingImportService {
|
||||
const args = DEP_ORDER.map((name) => deps[name]);
|
||||
return new BookingImportService(...(args as ConstructorParameters<typeof BookingImportService>));
|
||||
}
|
||||
|
||||
// The constructor's order, so a test names what it hands in instead of counting positions.
|
||||
const DEP_ORDER = [
|
||||
'extractor',
|
||||
'llmParse',
|
||||
'daysRepo',
|
||||
'reservationsRepo',
|
||||
'reservations',
|
||||
'guards',
|
||||
'budget',
|
||||
'addons',
|
||||
'realtime',
|
||||
'maps',
|
||||
'places',
|
||||
'uow',
|
||||
'origins',
|
||||
] as const;
|
||||
// confirm() checks the trip and the person's right itself: the trip is reachable, the role a plain user's.
|
||||
const tripAccess = vi.fn(async (): Promise<{ id: number; user_id: number } | undefined> => ({ id: 5, user_id: 1 }));
|
||||
// No earlier import holds any key unless a test says so.
|
||||
const findIdByExternal = vi.fn(async (): Promise<number | undefined> => undefined);
|
||||
const reservationsRepoStub = { findIdByExternal };
|
||||
// The origin bookkeeping of the venues a confirm creates; its own suite is place-origins.service.test.ts.
|
||||
const origins = { recordImported: vi.fn(async () => undefined) };
|
||||
// Runs the callback in place; the tests that care about the boundary wrap it to record it.
|
||||
@@ -47,21 +75,16 @@ function make(opts: { kit?: boolean; ai?: boolean; extract?: any; parse?: any })
|
||||
// services/placeService); only confirm() reaches it, so a bare create stub does.
|
||||
const places = { create: vi.fn() };
|
||||
return {
|
||||
svc: new BookingImportService(
|
||||
extractor as any,
|
||||
llmParse as any,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
reservations as never,
|
||||
permissionsStub as never,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
maps as never,
|
||||
places as never,
|
||||
uowStub as never,
|
||||
origins as never,
|
||||
),
|
||||
svc: buildService({
|
||||
extractor,
|
||||
llmParse,
|
||||
reservations,
|
||||
guards: guardsStub,
|
||||
maps,
|
||||
places,
|
||||
uow: uowStub,
|
||||
origins,
|
||||
}),
|
||||
extractor,
|
||||
llmParse,
|
||||
reservations,
|
||||
@@ -108,6 +131,16 @@ describe('BookingImportService.preview', () => {
|
||||
expect(res.files![0]).toEqual({ fileName: 'a.pdf', aiAvailable: true, aiUsed: true });
|
||||
});
|
||||
|
||||
it('reports how the AI reading of a file ended, where it ran', async () => {
|
||||
const { svc } = make({
|
||||
kit: true,
|
||||
ai: true,
|
||||
parse: async () => ({ kiItems: [], warnings: ['a.pdf: AI parsing failed — 429'], outcome: 'quota_exhausted' }),
|
||||
});
|
||||
const res = await svc.preview([file()], 'fallback-on-empty', 1);
|
||||
expect(res.files).toEqual([{ fileName: 'a.pdf', aiAvailable: true, aiUsed: true, outcome: 'quota_exhausted' }]);
|
||||
});
|
||||
|
||||
it('fallback-on-empty: skips the LLM when kitinerary already found items', async () => {
|
||||
const { svc, llmParse } = make({ kit: true, ai: true, extract: async () => [HOTEL_KI] });
|
||||
const res = await svc.preview([file()], 'fallback-on-empty', 1);
|
||||
@@ -251,24 +284,23 @@ describe('BookingImportService.confirm venue website (#2483)', () => {
|
||||
})),
|
||||
announceStayMirror: vi.fn(),
|
||||
announceCost: vi.fn(),
|
||||
verifyTripAccess: tripAccess,
|
||||
};
|
||||
const places = { create: vi.fn((_tripId: string, _input: { website?: string }) => ({ id: 7 })) };
|
||||
// No dates on a restaurant, so the day repositories are never reached.
|
||||
const svc = new BookingImportService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
reservations as never,
|
||||
permissionsStub as never,
|
||||
undefined as never,
|
||||
{ isAddonEnabled: () => false } as never,
|
||||
{ broadcast: vi.fn() } as never,
|
||||
{ geocodeQuery: vi.fn() } as never,
|
||||
places as never,
|
||||
uowStub as never,
|
||||
origins as never,
|
||||
);
|
||||
const svc = buildService({
|
||||
extractor: {},
|
||||
llmParse: {},
|
||||
reservationsRepo: reservationsRepoStub,
|
||||
reservations,
|
||||
guards: guardsStub,
|
||||
addons: { isAddonEnabled: () => false },
|
||||
realtime: { broadcast: vi.fn() },
|
||||
maps: { geocodeQuery: vi.fn() },
|
||||
places,
|
||||
uow: uowStub,
|
||||
origins,
|
||||
});
|
||||
const item = (website?: string) => ({
|
||||
type: 'restaurant',
|
||||
title: 'Dîner',
|
||||
@@ -278,6 +310,7 @@ describe('BookingImportService.confirm venue website (#2483)', () => {
|
||||
|
||||
const res = await svc.confirm(
|
||||
'5',
|
||||
1,
|
||||
[item('www.creperie.example/carte'), item('javascript:alert(1)'), item()],
|
||||
undefined,
|
||||
);
|
||||
@@ -317,6 +350,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
announceCost: vi.fn(() => {
|
||||
order.push('announceCost');
|
||||
}),
|
||||
verifyTripAccess: tripAccess,
|
||||
};
|
||||
const places = {
|
||||
create: vi.fn(async () => {
|
||||
@@ -348,21 +382,20 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
order.push(event);
|
||||
}),
|
||||
};
|
||||
const svc = new BookingImportService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
undefined as never,
|
||||
undefined as never,
|
||||
reservations as never,
|
||||
permissionsStub as never,
|
||||
budget as never,
|
||||
{ isAddonEnabled: async () => opts.budget ?? true } as never,
|
||||
realtime as never,
|
||||
{ geocodeQuery: vi.fn() } as never,
|
||||
places as never,
|
||||
uow as never,
|
||||
origins as never,
|
||||
);
|
||||
const svc = buildService({
|
||||
extractor: {},
|
||||
llmParse: {},
|
||||
reservationsRepo: reservationsRepoStub,
|
||||
reservations,
|
||||
guards: guardsStub,
|
||||
budget,
|
||||
addons: { isAddonEnabled: async () => opts.budget ?? true },
|
||||
realtime,
|
||||
maps: { geocodeQuery: vi.fn() },
|
||||
places,
|
||||
uow,
|
||||
origins,
|
||||
});
|
||||
return { svc, reservations, budget, places, realtime, order, costEvents };
|
||||
}
|
||||
const priced = {
|
||||
@@ -375,7 +408,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
it('BOOKING-IMPORT-TX-001: freezes the rate first, writes booking and cost in one call, announces the cost after the booking', async () => {
|
||||
const { svc, reservations, order, costEvents } = makeConfirm();
|
||||
|
||||
const res = await svc.confirm('5', [priced as never], 'sock');
|
||||
const res = await svc.confirm('5', 1, [priced as never], 'sock');
|
||||
|
||||
expect(res.created).toEqual([{ id: 1 }]);
|
||||
expect(reservations.createWithCostInTx).toHaveBeenCalledWith(
|
||||
@@ -428,7 +461,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
expect(preview.items).toHaveLength(1);
|
||||
|
||||
const { svc, reservations } = makeConfirm({ freeze: async () => {} });
|
||||
await svc.confirm('5', preview.items as never, undefined);
|
||||
await svc.confirm('5', 1, preview.items as never, undefined);
|
||||
|
||||
expect(reservations.createWithCostInTx).toHaveBeenCalledTimes(1);
|
||||
expect(reservations.createWithCostInTx).toHaveBeenCalledWith(
|
||||
@@ -440,12 +473,12 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
|
||||
it('BOOKING-IMPORT-TX-002: no cost without the Costs addon or without a price', async () => {
|
||||
const off = makeConfirm({ budget: false });
|
||||
await off.svc.confirm('5', [priced as never], undefined);
|
||||
await off.svc.confirm('5', 1, [priced as never], undefined);
|
||||
expect(off.budget.freezeForeignRate).not.toHaveBeenCalled();
|
||||
expect(off.reservations.createWithCostInTx).toHaveBeenCalledWith('5', expect.anything(), undefined);
|
||||
|
||||
const free = makeConfirm();
|
||||
await free.svc.confirm('5', [{ ...priced, metadata: { price: '0' } } as never], undefined);
|
||||
await free.svc.confirm('5', 1, [{ ...priced, metadata: { price: '0' } } as never], undefined);
|
||||
expect(free.budget.freezeForeignRate).not.toHaveBeenCalled();
|
||||
expect(free.reservations.createWithCostInTx).toHaveBeenCalledWith('5', expect.anything(), undefined);
|
||||
});
|
||||
@@ -460,7 +493,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
it('BOOKING-IMPORT-TX-004: writes the venue in the booking transaction and announces it after the commit', async () => {
|
||||
const { svc, places, reservations, order } = makeConfirm({ budget: false });
|
||||
|
||||
await svc.confirm('5', [atVenue as never], 'sock');
|
||||
await svc.confirm('5', 1, [atVenue as never], 'sock');
|
||||
|
||||
expect(order).toEqual([
|
||||
'begin',
|
||||
@@ -488,7 +521,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
try {
|
||||
const { svc, realtime, order } = makeConfirm({ budget: false, failWrite: true });
|
||||
|
||||
const res = await svc.confirm('5', [atVenue as never], 'sock');
|
||||
const res = await svc.confirm('5', 1, [atVenue as never], 'sock');
|
||||
|
||||
expect(res.created).toEqual([]);
|
||||
// The place insert ran inside the transaction the failure rolls back, never on its own.
|
||||
@@ -507,7 +540,7 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
throw new Error('rates down');
|
||||
},
|
||||
});
|
||||
const res = await svc.confirm('5', [priced as never], undefined);
|
||||
const res = await svc.confirm('5', 1, [priced as never], undefined);
|
||||
expect(res.created).toEqual([{ id: 1 }]);
|
||||
expect(reservations.createWithCostInTx).toHaveBeenCalledWith('5', expect.anything(), undefined);
|
||||
} finally {
|
||||
@@ -515,3 +548,168 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('BookingImportService.confirm reports every item it did not create', () => {
|
||||
function makeReport(write: () => Promise<unknown>) {
|
||||
const reservations = {
|
||||
createWithCostInTx: vi.fn(write),
|
||||
announceStayMirror: vi.fn(),
|
||||
announceCost: vi.fn(),
|
||||
verifyTripAccess: tripAccess,
|
||||
};
|
||||
const svc = buildService({
|
||||
extractor: {},
|
||||
llmParse: {},
|
||||
reservationsRepo: reservationsRepoStub,
|
||||
reservations,
|
||||
guards: guardsStub,
|
||||
addons: { isAddonEnabled: async () => false },
|
||||
realtime: { broadcast: vi.fn() },
|
||||
maps: { geocodeQuery: vi.fn() },
|
||||
places: { create: vi.fn() },
|
||||
uow: uowStub,
|
||||
origins,
|
||||
});
|
||||
return { svc, reservations };
|
||||
}
|
||||
const NO_LOCAL_TIME = { timezone: null, local_time: null, local_date: null };
|
||||
const flight = {
|
||||
type: 'flight',
|
||||
title: 'LH 716',
|
||||
confirmation_number: ' abc 123 ',
|
||||
reservation_time: '2026-09-01T10:00',
|
||||
endpoints: [
|
||||
{ role: 'from', name: 'Frankfurt', code: 'FRA', lat: 50, lng: 8.5, ...NO_LOCAL_TIME },
|
||||
{ role: 'to', name: 'Tokyo Narita', code: 'NRT', lat: 35.7, lng: 140.4, ...NO_LOCAL_TIME },
|
||||
],
|
||||
source: { fileName: 'ticket.pdf', index: 0 },
|
||||
};
|
||||
|
||||
it('BOOKING-IMPORT-REPORT-001: a referenced booking is written with its origin, sync off', async () => {
|
||||
const { svc, reservations } = makeReport(async () => ({
|
||||
reservation: { id: 1 },
|
||||
accommodationCreated: false,
|
||||
costEvents: [],
|
||||
stayMirror: {},
|
||||
}));
|
||||
|
||||
const res = await svc.confirm('5', 1, [flight as never], undefined);
|
||||
|
||||
expect(res).toEqual({ created: [{ id: 1 }], failed: [] });
|
||||
expect(findIdByExternal).toHaveBeenCalledWith(5, 'import', 'ABC123|flight|2026-09-01|fra-nrt');
|
||||
expect(reservations.createWithCostInTx).toHaveBeenCalledWith(
|
||||
'5',
|
||||
expect.objectContaining({
|
||||
external_source: 'import',
|
||||
external_id: 'ABC123|flight|2026-09-01|fra-nrt',
|
||||
sync_enabled: false,
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('BOOKING-IMPORT-REPORT-002: the origin an item names itself is ignored, and an item without a reference has none', async () => {
|
||||
const { svc, reservations } = makeReport(async () => ({
|
||||
reservation: { id: 2 },
|
||||
accommodationCreated: false,
|
||||
costEvents: [],
|
||||
stayMirror: {},
|
||||
}));
|
||||
const posing = { ...flight, confirmation_number: null, external_source: 'airtrail', external_id: '42' };
|
||||
|
||||
await svc.confirm('5', 1, [posing as never], undefined);
|
||||
|
||||
expect(findIdByExternal).not.toHaveBeenCalled();
|
||||
const written = (reservations.createWithCostInTx.mock.calls[0] as unknown[])[1] as Record<string, unknown>;
|
||||
expect(written).not.toHaveProperty('external_source');
|
||||
expect(written).not.toHaveProperty('external_id');
|
||||
});
|
||||
|
||||
it('BOOKING-IMPORT-REPORT-003: a booking already imported, one the index refuses and one that fails are each named', async () => {
|
||||
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
const { UniqueConstraintViolationException } = await import('@mikro-orm/core');
|
||||
const writes = [
|
||||
() => Promise.reject(new UniqueConstraintViolationException(new Error('UNIQUE constraint failed'))),
|
||||
() => Promise.reject(new Error('disk full')),
|
||||
];
|
||||
const { svc } = makeReport(async () => {
|
||||
const write = writes.shift();
|
||||
if (!write) throw new Error('the case planned no further write');
|
||||
return write();
|
||||
});
|
||||
findIdByExternal.mockResolvedValueOnce(9);
|
||||
|
||||
const res = await svc.confirm(
|
||||
'5',
|
||||
1,
|
||||
[
|
||||
flight,
|
||||
{ ...flight, reservation_time: '2026-09-02T10:00' },
|
||||
{ ...flight, confirmation_number: null },
|
||||
] as never,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(res).toEqual({
|
||||
created: [],
|
||||
failed: [
|
||||
{ index: 0, reason: 'duplicate' },
|
||||
{ index: 1, reason: 'duplicate' },
|
||||
{ index: 2, reason: 'write_failed' },
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
quiet.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('BOOKING-IMPORT-REPORT-004: refuses a trip the person cannot reach, and one whose bookings they may not edit', async () => {
|
||||
const { svc, reservations } = makeReport(async () => ({}));
|
||||
tripAccess.mockResolvedValueOnce(undefined);
|
||||
await expect(svc.confirm('5', 1, [flight as never], undefined)).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
guardsStub.hasTripPermission.mockResolvedValueOnce(false);
|
||||
await expect(svc.confirm('5', 2, [flight as never], undefined)).rejects.toMatchObject({ status: 403 });
|
||||
// The right is asked of the shared guard for that person and trip, which reads their role.
|
||||
expect(guardsStub.hasTripPermission).toHaveBeenLastCalledWith('reservation_edit', '5', 2);
|
||||
expect(reservations.createWithCostInTx).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('BookingImportService: reading a forwarded mail', () => {
|
||||
it('reads the whole mail first and the attachments only when it gave nothing', async () => {
|
||||
const { svc, extractor } = make({ kit: true, extract: async () => [HOTEL_KI] });
|
||||
const items = await svc.readMailBookings(Buffer.from('mail'), [{ fileName: 'a.pdf', data: Buffer.from('a') }], 1);
|
||||
expect(items).toHaveLength(1);
|
||||
expect(extractor.extract).toHaveBeenCalledTimes(1);
|
||||
expect(extractor.extract.mock.calls[0][1]).toBe('mail.eml');
|
||||
});
|
||||
|
||||
it('falls back to each attachment when the mail as a whole names no booking', async () => {
|
||||
const extract = vi.fn(async (_buffer: Buffer, name: string) => (name === 'a.pdf' ? [HOTEL_KI] : []));
|
||||
const { svc } = make({ kit: true, extract });
|
||||
const items = await svc.readMailBookings(Buffer.from('mail'), [{ fileName: 'a.pdf', data: Buffer.from('a') }], 1);
|
||||
expect(items.map((item) => item.source.fileName)).toEqual(['a.pdf']);
|
||||
expect(await svc.readMailBookings(Buffer.from('mail'), [], 1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads nothing where kitinerary is not installed', async () => {
|
||||
const { svc, extractor } = make({ kit: false, ai: true });
|
||||
expect(await svc.readMailBookings(Buffer.from('mail'), [], 1)).toEqual([]);
|
||||
expect(extractor.extract).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('maps an AI reading of a mail to items flagged for review', async () => {
|
||||
const { svc } = make({});
|
||||
const [item] = await svc.mapAiReservations([HOTEL_KI], 'mail');
|
||||
expect(item).toMatchObject({ type: 'hotel', needs_review: true, confirmation_number: 'ABC' });
|
||||
});
|
||||
|
||||
it('names the key a booking is stored under', () => {
|
||||
const { svc } = make({});
|
||||
const item = { type: 'hotel', title: 'Hotel X', confirmation_number: 'ab c', source: { fileName: 'm', index: 0 } };
|
||||
expect(svc.externalKey({ ...item, _accommodation: { check_in: '2026-06-11' } })).toBe('ABC|hotel|2026-06-11|');
|
||||
expect(svc.externalKey({ ...item, confirmation_number: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { IMPORT_SOURCE, importExternalId } from '../../../../src/nest/booking-import/booking-origin';
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const item = (fields: Partial<BookingImportPreviewItem>): BookingImportPreviewItem => ({
|
||||
type: 'flight',
|
||||
title: 'LH 716',
|
||||
source: { fileName: 'ticket.pdf', index: 0 },
|
||||
...fields,
|
||||
});
|
||||
|
||||
const endpoint = (role: 'from' | 'to', name: string, code: string | null) => ({
|
||||
role,
|
||||
sequence: role === 'from' ? 0 : 1,
|
||||
name,
|
||||
code,
|
||||
lat: 0,
|
||||
lng: 0,
|
||||
timezone: null,
|
||||
local_time: null,
|
||||
local_date: null,
|
||||
});
|
||||
|
||||
describe('importExternalId', () => {
|
||||
it('BOOKING-ORIGIN-001: no reference, no key', () => {
|
||||
expect(importExternalId(item({}))).toBeNull();
|
||||
expect(importExternalId(item({ confirmation_number: ' ' }))).toBeNull();
|
||||
expect(IMPORT_SOURCE).toBe('import');
|
||||
});
|
||||
|
||||
it('BOOKING-ORIGIN-002: the reference is read without spacing and case, the route by code before name', () => {
|
||||
const outbound = item({
|
||||
confirmation_number: ' abc 123',
|
||||
reservation_time: '2026-09-01T10:00',
|
||||
endpoints: [endpoint('from', 'Frankfurt', 'FRA'), endpoint('to', 'Tokyo Narita', null)],
|
||||
});
|
||||
expect(importExternalId(outbound)).toBe('ABC123|flight|2026-09-01|fra-tokyo narita');
|
||||
});
|
||||
|
||||
it('BOOKING-ORIGIN-003: the legs of one reference get keys of their own', () => {
|
||||
const there = item({ confirmation_number: 'ABC123', reservation_time: '2026-09-01T10:00' });
|
||||
const back = item({ confirmation_number: 'ABC123', reservation_time: '2026-09-15T10:00' });
|
||||
expect(importExternalId(there)).not.toBe(importExternalId(back));
|
||||
});
|
||||
|
||||
it('BOOKING-ORIGIN-004: a stay is keyed by its check-in, and an overlong key is cut', () => {
|
||||
const stay = item({
|
||||
type: 'hotel',
|
||||
confirmation_number: 'H-77',
|
||||
_accommodation: { check_in: '2026-09-02T15:00', check_out: '2026-09-04T11:00' },
|
||||
});
|
||||
expect(importExternalId(stay)).toBe('H-77|hotel|2026-09-02|');
|
||||
expect(importExternalId(item({ confirmation_number: 'X'.repeat(500) }))).toHaveLength(200);
|
||||
});
|
||||
});
|
||||
@@ -634,3 +634,51 @@ describe('kitinerary mapper: a prompt-shaped AI lodging (#2477)', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('kitinerary mapper: the seat as KItinerary writes it', () => {
|
||||
it('reads a flight seat from airplaneSeat', () => {
|
||||
const node = {
|
||||
...flight('CE9P8V', SFO, JFK, '2026-06-11T10:00:00', '2026-06-11T18:30:00', '450'),
|
||||
airplaneSeat: '4D',
|
||||
};
|
||||
const { items } = mapReservations(legs(node), 'test.json');
|
||||
expect(items[0].metadata).toMatchObject({ seat: '4D' });
|
||||
});
|
||||
|
||||
it('reads a seat from reservedTicket.ticketedSeat.seatNumber', () => {
|
||||
const node = {
|
||||
...flight('CE9P8V', SFO, JFK, '2026-06-11T10:00:00', '2026-06-11T18:30:00', '450'),
|
||||
reservedTicket: { ticketedSeat: { seatNumber: '23A' } },
|
||||
};
|
||||
const { items } = mapReservations(legs(node), 'test.json');
|
||||
expect(items[0].metadata).toMatchObject({ seat: '23A' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('kitinerary mapper: the seat on each leg of a connecting flight', () => {
|
||||
it('keeps every leg its own seat', () => {
|
||||
const first = {
|
||||
...flight('ABC123', FRA, BER, '2026-06-11T10:00:00', '2026-06-11T12:00:00', 'LH 100'),
|
||||
airplaneSeat: '12C',
|
||||
};
|
||||
const second = {
|
||||
...flight('ABC123', BER, HND, '2026-06-11T14:30:00', '2026-06-11T23:30:00', 'LH 200'),
|
||||
airplaneSeat: '40A',
|
||||
};
|
||||
const { items } = mapReservations(legs(first, second), 'test.json');
|
||||
const legsMeta = (items[0].metadata as { legs: { seat?: string }[] }).legs;
|
||||
expect(legsMeta.map((leg) => leg.seat)).toEqual(['12C', '40A']);
|
||||
});
|
||||
|
||||
it('leaves the seat off a leg that has none', () => {
|
||||
const first = flight('ABC123', FRA, BER, '2026-06-11T10:00:00', '2026-06-11T12:00:00', 'LH 100');
|
||||
const second = {
|
||||
...flight('ABC123', BER, HND, '2026-06-11T14:30:00', '2026-06-11T23:30:00', 'LH 200'),
|
||||
airplaneSeat: '40A',
|
||||
};
|
||||
const { items } = mapReservations(legs(first, second), 'test.json');
|
||||
const legsMeta = (items[0].metadata as { legs: Record<string, unknown>[] }).legs;
|
||||
expect(legsMeta[0]).not.toHaveProperty('seat');
|
||||
expect(legsMeta[1]).toMatchObject({ seat: '40A' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1437,6 +1437,27 @@ describe('calculateSettlement: currencies shown in whole units (#2604)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('a bill in a won display currency on a euro trip is split in whole won, and settle-up clears it', async () => {
|
||||
// Read in won, a won bill counts as typed (#2965) and skips the conversion that
|
||||
// rounds to whole won, so it has to be split in whole won itself: 3,333.33 each
|
||||
// printed as -3,333 / -3,333 beside +6,667 again.
|
||||
const fx = { base: 'KRW', tripCurrency: 'EUR', rates: { EUR: 1, KRW: 1500 } };
|
||||
const items = [{ ...makeItem(1, 10000), currency: 'KRW', exchange_rate: 1500 } as BudgetItem];
|
||||
const members = [makeMember(1, 1, 'alice'), makeMember(1, 2, 'bob'), makeMember(1, 3, 'carol')];
|
||||
const payers = [makePayer(1, 1, 10000, 'alice')];
|
||||
await setupDb(items, members, payers);
|
||||
|
||||
const result = await budget.calculateSettlement(1, fx);
|
||||
expect(result.currency).toBe('KRW');
|
||||
expectWholeAndSquare(result);
|
||||
expect(result.balances.map((b) => b.balance).sort((x, y) => x - y)).toEqual([-3334, -3333, 6667]);
|
||||
|
||||
const after = await settleEverything(items, members, payers, fx, 'KRW');
|
||||
expectWholeAndSquare(after);
|
||||
expect(after.balances.every((b) => b.balance === 0)).toBe(true);
|
||||
expect(after.flows).toEqual([]);
|
||||
});
|
||||
|
||||
it('a two-decimal display currency keeps its cents', async () => {
|
||||
// The euro case the rest of this file pins, read once more beside the won ones:
|
||||
// 10.00 three ways stays 3.34 / 3.33 / 3.33, not whole euros.
|
||||
@@ -1629,6 +1650,40 @@ describe('calculateSettlement: bills in the display currency (#2965)', () => {
|
||||
expect(centSum(later.balances.map((b) => b.balance))).toBe(0);
|
||||
});
|
||||
|
||||
it('settled when the halves point opposite ways, it stays settled when the yen moves', async () => {
|
||||
// Bob paid a 100 EUR train for both, Alice a 100,000 yen hotel for both: Alice
|
||||
// owes Bob 50 EUR in euros, Bob owes Alice 50,000 yen. Bob pays the net in euros.
|
||||
// The euro credit used to stay in euros beside the yen it was netted with, and
|
||||
// the balance reopened as soon as the rate moved.
|
||||
const items = () => [
|
||||
{ ...makeItem(1, 100), currency: 'EUR', exchange_rate: 1 / 176.37 } as BudgetItem,
|
||||
{ ...makeItem(2, 100000) } as BudgetItem,
|
||||
];
|
||||
const members = () => [...pair(), makeMember(2, 1, 'alice'), makeMember(2, 2, 'bob')];
|
||||
const payers = () => [makePayer(1, 2, 100, 'bob'), makePayer(2, 1, 100000, 'alice')];
|
||||
await setupDb(items(), members(), payers());
|
||||
const offer = (await budget.calculateSettlement(1, today)).flows;
|
||||
expect(offer).toHaveLength(1);
|
||||
expect(offer[0].from.user_id).toBe(2);
|
||||
await setupDb(items(), members(), payers(), [makeSettlementRow(5, 2, 1, offer[0].amount, 'EUR', 1 / 176.73)]);
|
||||
const results = await Promise.all(
|
||||
[1 / 176.73, 1 / 160, 1 / 195].map((eurPerYen) =>
|
||||
budget.calculateSettlement(1, { ...today, rates: { JPY: 1, EUR: eurPerYen } }),
|
||||
),
|
||||
);
|
||||
for (const result of results) {
|
||||
expect(result.balances.map((b) => b.balance)).toEqual([0, 0]);
|
||||
expect(result.flows).toEqual([]);
|
||||
for (const f of result.finalBudgets) {
|
||||
expect(f.sources.moved.reduce((a, r) => a + r.cents, 0)).toBe(Math.round(f.reimbursed * 100));
|
||||
expect(f.final).toBeCloseTo(f.expenses - f.reimbursed - f.pending, 2);
|
||||
}
|
||||
}
|
||||
// What Bob sent is what Alice received, read on the day it was sent.
|
||||
const alice = results[0].finalBudgets.find((f) => f.user_id === 1);
|
||||
expect(alice?.reimbursed).toBe(offer[0].amount);
|
||||
});
|
||||
|
||||
it('read in the trip currency nothing changes: the bill goes through its frozen rate', async () => {
|
||||
await setupDb(flight(), pair(), paid());
|
||||
const result = await budget.calculateSettlement(1, { base: 'JPY', tripCurrency: 'JPY', rates: null });
|
||||
|
||||
@@ -30,7 +30,7 @@ import { ReservationsService } from '../../../src/nest/reservations/reservations
|
||||
import { ReservationsReadService } from '../../../src/nest/reservations/reservations-read.service';
|
||||
import { BudgetService } from '../../../src/nest/budget/budget.service';
|
||||
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
|
||||
import { CalendarService, foldICS } from '../../../src/nest/calendar/calendar.service';
|
||||
import { CalendarService, calendarOptionsFromQuery, foldICS } from '../../../src/nest/calendar/calendar.service';
|
||||
import { CalendarModule } from '../../../src/nest/calendar/calendar.module';
|
||||
import { expectRegisteredProvider } from '../../helpers/module-providers';
|
||||
import { notificationsStub } from '../../helpers/notifications';
|
||||
@@ -1682,6 +1682,58 @@ describe('folded quirk branches', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-day summaries (#2602)', () => {
|
||||
async function tripWithEveryKindOfDay() {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { title: 'Lisbon', start_date: '2025-06-02', end_date: '2025-06-03' });
|
||||
// A dated trip comes with its days; the first one is the 2nd of June.
|
||||
const [day] = await findRows(orm, Days, { trip: trip.id }, { id: 'asc' });
|
||||
const untimed = createPlace(testDb, trip.id, { name: 'Untimed Spot' });
|
||||
createDayAssignment(testDb, day.id, untimed.id);
|
||||
createDayNote(testDb, day.id, trip.id, { text: 'Buy tram tickets' });
|
||||
const timed = createPlace(testDb, trip.id, { name: 'Castle Visit' });
|
||||
const assignment = createDayAssignment(testDb, day.id, timed.id);
|
||||
await updateRows(orm, DayAssignments, { id: assignment.id }, { assignment_time: '10:00' });
|
||||
return trip;
|
||||
}
|
||||
|
||||
it('CAL-2602-001: are in the calendar by default', async () => {
|
||||
const trip = await tripWithEveryKindOfDay();
|
||||
|
||||
const { ics } = await svc.exportICS(trip.id);
|
||||
|
||||
expect(ics).toContain('SUMMARY:Day 1');
|
||||
});
|
||||
|
||||
it('CAL-2602-002: dayEvents false leaves them out and keeps the trip and its timed stops', async () => {
|
||||
const trip = await tripWithEveryKindOfDay();
|
||||
|
||||
const { ics } = await svc.exportICS(trip.id, { dayEvents: false });
|
||||
|
||||
expect(ics).not.toContain('SUMMARY:Day 1');
|
||||
expect(ics).not.toContain('Untimed Spot');
|
||||
expect(ics).not.toContain('Buy tram tickets');
|
||||
expect(ics).toContain('SUMMARY:Lisbon');
|
||||
expect(ics).toContain('SUMMARY:Castle Visit');
|
||||
});
|
||||
|
||||
it('CAL-2602-003: buildTripCalendar drops the same events for the feeds', async () => {
|
||||
const trip = await tripWithEveryKindOfDay();
|
||||
|
||||
const all = await svc.buildTripCalendar(trip.id);
|
||||
const lean = await svc.buildTripCalendar(trip.id, { dayEvents: false });
|
||||
|
||||
expect(lean.events).toHaveLength(all.events.length - 1);
|
||||
expect(lean.events.some((event) => event.includes('UID:trek-day-'))).toBe(false);
|
||||
});
|
||||
|
||||
it('CAL-2602-004: days=0 in the query turns them off, days=1 or nothing keeps them', () => {
|
||||
expect(calendarOptionsFromQuery({ days: '0' })).toEqual({ dayEvents: false });
|
||||
expect(calendarOptionsFromQuery({ days: '1' })).toEqual({ dayEvents: true });
|
||||
expect(calendarOptionsFromQuery({})).toEqual({ dayEvents: true });
|
||||
});
|
||||
});
|
||||
|
||||
// foldICS is the last thing that touches the bytes of both the download and the
|
||||
// feed, and it is exported, so it is pinned directly instead of through a trip.
|
||||
describe('foldICS', () => {
|
||||
|
||||
@@ -343,6 +343,9 @@ describe('listMessages', () => {
|
||||
expect(msgs).toHaveLength(1);
|
||||
expect(msgs[0].text).toBe('');
|
||||
expect(msgs[0].deleted).toBe(1);
|
||||
// Gone from the row itself, not only blanked on the way out.
|
||||
const row = await findRow(orm, CollabMessages, { id: msgs[0].id });
|
||||
expect(row?.text).toBe('');
|
||||
});
|
||||
|
||||
it('COLLAB-SVC-013b: blanks reply_text when the quoted message was deleted', async () => {
|
||||
|
||||
@@ -407,6 +407,15 @@ describe('CollectionsController', () => {
|
||||
expect(svc.exportCollectionGpx).toHaveBeenCalledWith(1, 3);
|
||||
});
|
||||
|
||||
it('exports the list as KML for Google My Maps the same way (#1866)', async () => {
|
||||
const exported = { name: 'Lisbon', kml: '<kml/>', pins: 0, omitted: 0 };
|
||||
const svc = makeService({ exportCollectionKml: vi.fn().mockResolvedValue(exported) });
|
||||
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
|
||||
|
||||
expect(await c.exportCollectionKml(user, '3')).toBe(exported);
|
||||
expect(svc.exportCollectionKml).toHaveBeenCalledWith(1, 3);
|
||||
});
|
||||
|
||||
it('hands back the file a GPX was read into', () => {
|
||||
const read = { file: { name: 'Lisbon' }, skipped: 1, track_points: 4 };
|
||||
const svc = makeService({ readCollectionGpx: vi.fn().mockReturnValue(read) });
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
/**
|
||||
* The link helpers of the collections domain, which read and write the JSON
|
||||
* TEXT column a list or a saved place keeps its links in.
|
||||
* COLLECTIONS-HELPERS-001 to 003.
|
||||
* The pure helpers of the collections domain: the link helpers, which read and
|
||||
* write the JSON TEXT column a list or a saved place keeps its links in, the
|
||||
* listing fields an update writes, the cursor of a page of places, and a saved
|
||||
* place as the list file carries it. COLLECTIONS-HELPERS-001 to 009.
|
||||
*/
|
||||
import { parseLinks, serializeLinks } from '../../../src/nest/collections/collections.helpers';
|
||||
import type { CollectionPlaceRow } from '../../../src/db/repositories/Collections.repository';
|
||||
import {
|
||||
decodePlacesCursor,
|
||||
encodePlacesCursor,
|
||||
filePlaceOf,
|
||||
listingWriteOf,
|
||||
parseLinks,
|
||||
serializeLinks,
|
||||
} from '../../../src/nest/collections/collections.helpers';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -29,3 +38,121 @@ describe('serializeLinks', () => {
|
||||
expect(serializeLinks(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listingWriteOf', () => {
|
||||
it('COLLECTIONS-HELPERS-004: writes each provider id, contact and price field the update names, null clearing it', () => {
|
||||
expect(
|
||||
listingWriteOf({
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: null,
|
||||
osm_id: 'node/42',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: null,
|
||||
price: 0,
|
||||
currency: 'EUR',
|
||||
}),
|
||||
).toEqual({
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: null,
|
||||
osm_id: 'node/42',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: null,
|
||||
price: 0,
|
||||
currency: 'EUR',
|
||||
});
|
||||
});
|
||||
|
||||
it('COLLECTIONS-HELPERS-005: leaves out what the update does not name, so the stored value stays', () => {
|
||||
expect(listingWriteOf({ name: 'Septime', notes: 'Book ahead' })).toEqual({});
|
||||
expect(listingWriteOf({ website: undefined, phone: '+33 1' })).toEqual({ phone: '+33 1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodePlacesCursor / decodePlacesCursor', () => {
|
||||
it('COLLECTIONS-HELPERS-006: a cursor gives back the position it was made from', () => {
|
||||
const position = { sortOrder: 3, createdAt: '2026-05-01 10:00:00', id: 42 };
|
||||
const cursor = encodePlacesCursor(position);
|
||||
expect(cursor).toMatch(/^[A-Za-z0-9_-]+$/);
|
||||
expect(decodePlacesCursor(cursor)).toEqual(position);
|
||||
expect(decodePlacesCursor(encodePlacesCursor({ sortOrder: -1, createdAt: '', id: 1 }))).toEqual({
|
||||
sortOrder: -1,
|
||||
createdAt: '',
|
||||
id: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('COLLECTIONS-HELPERS-007: anything else reads as no position', () => {
|
||||
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
expect(decodePlacesCursor('not-a-cursor')).toBeNull();
|
||||
expect(decodePlacesCursor('')).toBeNull();
|
||||
expect(decodePlacesCursor(encode({ id: 1 }))).toBeNull();
|
||||
expect(decodePlacesCursor(encode([0, '2026-05-01 10:00:00']))).toBeNull();
|
||||
expect(decodePlacesCursor(encode([0.5, '2026-05-01 10:00:00', 1]))).toBeNull();
|
||||
expect(decodePlacesCursor(encode([0, '2026-05-01 10:00:00', 0]))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('filePlaceOf', () => {
|
||||
const row: CollectionPlaceRow = {
|
||||
id: 9,
|
||||
collection_id: 4,
|
||||
owner_id: 1,
|
||||
saved_by: 1,
|
||||
name: 'Septime',
|
||||
description: 'Natural wine',
|
||||
lat: 48.853,
|
||||
lng: 2.381,
|
||||
address: '80 Rue de Charonne',
|
||||
category_id: 3,
|
||||
price: 45,
|
||||
currency: 'EUR',
|
||||
notes: 'Book ahead',
|
||||
image_url: 'https://images.example/septime.jpg',
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: null,
|
||||
osm_id: 'node/42',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
status: 'revisit',
|
||||
source_trip_id: 7,
|
||||
source_place_id: 70,
|
||||
links: JSON.stringify(links),
|
||||
sort_order: 0,
|
||||
created_at: '2026-05-01 10:00:00',
|
||||
updated_at: null,
|
||||
category_name: 'Restaurant',
|
||||
category_color: '#ff0000',
|
||||
category_icon: 'utensils',
|
||||
};
|
||||
|
||||
it('COLLECTIONS-HELPERS-008: a saved place as the list file carries it: no ids, the category by name, the labels given', () => {
|
||||
expect(filePlaceOf(row, ['Dinner'])).toEqual({
|
||||
name: 'Septime',
|
||||
description: 'Natural wine',
|
||||
lat: 48.853,
|
||||
lng: 2.381,
|
||||
address: '80 Rue de Charonne',
|
||||
notes: 'Book ahead',
|
||||
price: 45,
|
||||
currency: 'EUR',
|
||||
website: 'https://septime-charonne.fr',
|
||||
phone: '+33 1 43 67 38 29',
|
||||
image_url: 'https://images.example/septime.jpg',
|
||||
google_place_id: 'ChIJseptime',
|
||||
google_ftid: null,
|
||||
osm_id: 'node/42',
|
||||
status: 'revisit',
|
||||
links,
|
||||
category: 'Restaurant',
|
||||
labels: ['Dinner'],
|
||||
});
|
||||
});
|
||||
|
||||
it('COLLECTIONS-HELPERS-009: an upload of this server stays behind, it resolves nowhere else', () => {
|
||||
expect(filePlaceOf({ ...row, image_url: '/uploads/places/septime.jpg' }, []).image_url).toBeNull();
|
||||
expect(filePlaceOf({ ...row, image_url: null, links: null }, [])).toMatchObject({
|
||||
image_url: null,
|
||||
links: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -285,6 +285,16 @@ describe('saved places + dedup', () => {
|
||||
expect(res.place!.tags?.map((t) => t.name)).toContain('food');
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-012b: savePlace leaves out a tag that belongs to a trip', async () => {
|
||||
const u = createUser(testDb).user;
|
||||
const own = createTag(testDb, u.id, { name: 'food' });
|
||||
const ofTrip = createTag(testDb, u.id, { name: 'Monument' });
|
||||
await updateRows(await orm(), Tags, { id: ofTrip.id }, { trip: createTrip(testDb, u.id).id });
|
||||
const col = await svc.createCollection(u.id, { name: 'Tagged' });
|
||||
const res = await svc.savePlace(u.id, { collection_id: col.id, name: 'Ramen', tag_ids: [own.id, ofTrip.id] });
|
||||
expect(res.place?.tags?.map((t) => t.name)).toEqual(['food']);
|
||||
});
|
||||
|
||||
it('CL49 (Plan 3h Task 7 review, M1 coverage): updatePlace with tag_ids rewrites the tag set (CollectionPlacesRepository.deleteTags)', async () => {
|
||||
const u = createUser(testDb).user;
|
||||
const food = createTag(testDb, u.id, { name: 'food' });
|
||||
@@ -700,6 +710,24 @@ describe('deleteCollection', () => {
|
||||
expect(await placesIn(col.id)).toEqual({ n: 0 });
|
||||
expect(await membersOf(col.id)).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-040b: deleting a list releases its cover and the images of its saved places (#2924)', async () => {
|
||||
const owner = createUser(testDb).user;
|
||||
const col = await svc.createCollection(owner.id, { name: 'Doomed' });
|
||||
const files = ['list-cover.jpg', 'list-place-a.jpg', 'list-place-b.jpg'].map((name) => {
|
||||
const filePath = path.join(storageFx.root, name);
|
||||
fs.writeFileSync(filePath, 'jpeg-bytes');
|
||||
return filePath;
|
||||
});
|
||||
await svc.setCollectionCover(owner.id, col.id, '/uploads/covers/list-cover.jpg');
|
||||
await svc.savePlace(owner.id, { collection_id: col.id, name: 'A', image_url: '/uploads/places/list-place-a.jpg' });
|
||||
await svc.savePlace(owner.id, { collection_id: col.id, name: 'B', image_url: '/uploads/places/list-place-b.jpg' });
|
||||
await svc.savePlace(owner.id, { collection_id: col.id, name: 'No image' });
|
||||
|
||||
await svc.deleteCollection(owner.id, col.id);
|
||||
|
||||
expect(files.map((file) => fs.existsSync(file))).toEqual([false, false, false]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── owner_id semantics: member account deletion keeps shared content ─────────
|
||||
|
||||
@@ -153,6 +153,7 @@ beforeAll(async () => {
|
||||
await createTestJourneyPhotosRepo(testDb),
|
||||
await createTestJourneyEntryPhotosRepo(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
{ releaseValues: async () => 0 } as never, // StorageReleaseService
|
||||
),
|
||||
makeStorageFixture('').storage,
|
||||
await accommodationsOver(testDb),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user