mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
fix(ci): green the quick-win round on the server, the shared contracts and the plugin facts
The trips entity takes costs_mode as the generator writes it, the plugin output contract publishes it, and the hand-built test schemas carry it. The new MCP fields come from @trek/shared, the link tool tests join the collab file that already mocks the database, oidc_auto_redirect is the operator's on a managed install, and the tests follow the KML service, the dated trip days and the zod pipe.
This commit is contained in:
@@ -434,6 +434,7 @@ export const PLUGIN_ENTITY_FIELDS = {
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'reminder_sent_for',
|
||||
'costs_mode',
|
||||
'day_count',
|
||||
'place_count',
|
||||
'is_owner',
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 1555,
|
||||
"@typescript-eslint/no-non-null-assertion": 1754,
|
||||
"@typescript-eslint/no-non-null-assertion": 1747,
|
||||
"@typescript-eslint/no-require-imports": 25,
|
||||
"@typescript-eslint/no-unsafe-function-type": 7,
|
||||
"@typescript-eslint/no-unused-vars": 96,
|
||||
|
||||
@@ -58,7 +58,7 @@ export class Trips {
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
reminder_sent_for?: string | null;
|
||||
costs_mode: string & Opt = 'split';
|
||||
costs_mode: TTripsCostsMode & Opt = TripsCostsMode.SPLIT;
|
||||
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
|
||||
assistant_threads_collection = new Collection<AssistantThreads>(this);
|
||||
budget_category_order_collection = new Collection<BudgetCategoryOrder>(this);
|
||||
@@ -99,6 +99,13 @@ export class Trips {
|
||||
trip_photos_collection = new Collection<TripPhotos>(this);
|
||||
}
|
||||
|
||||
export const TripsCostsMode = {
|
||||
SPLIT: 'split',
|
||||
TOTALS: 'totals',
|
||||
} as const;
|
||||
|
||||
export type TTripsCostsMode = (typeof TripsCostsMode)[keyof typeof TripsCostsMode];
|
||||
|
||||
export const TripsSchema = defineEntity({
|
||||
class: Trips,
|
||||
repository: () => TripsRepository,
|
||||
@@ -125,7 +132,7 @@ export const TripsSchema = defineEntity({
|
||||
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`).index('idx_trips_created_at'),
|
||||
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
reminder_sent_for: p.text().nullable(),
|
||||
costs_mode: p.text().default('split'),
|
||||
costs_mode: p.enum(() => TripsCostsMode).default('split'),
|
||||
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('trip').hidden(),
|
||||
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('trip').hidden(),
|
||||
budget_category_order_collection: () => p.oneToMany(BudgetCategoryOrder).mappedBy('trip').hidden(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { QueryFlag } from '@mikro-orm/core';
|
||||
import type { Trips } from '../entities/Trips.entity';
|
||||
import type { TTripsCostsMode, Trips } from '../entities/Trips.entity';
|
||||
import { coalesceParam, currentTimestamp, nowDateOffset } from '../dialect/sql-functions';
|
||||
import type { AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
@@ -36,7 +36,7 @@ export interface TripRawRow {
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
reminder_sent_for: string | null;
|
||||
costs_mode: string;
|
||||
costs_mode: TTripsCostsMode;
|
||||
}
|
||||
|
||||
const _tripRawRowKeys: AssertRowKeys<TripRawRow, Trips> = true;
|
||||
@@ -564,7 +564,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
currency: string | null;
|
||||
cover_image: string | null;
|
||||
reminder_days: number;
|
||||
costs_mode: string;
|
||||
costs_mode: TTripsCostsMode;
|
||||
}): Promise<number> {
|
||||
return await this.insert({
|
||||
user: input.user_id,
|
||||
|
||||
@@ -16,7 +16,12 @@ import { collabFeatureGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { CollabService } from './collab.service';
|
||||
import { collabLinkCreateRequestSchema, collabLinkUpdateRequestSchema, idSchema } from '@trek/shared';
|
||||
import {
|
||||
collabLinkCreateRequestSchema,
|
||||
collabLinkPinnedSchema,
|
||||
collabLinkUpdateRequestSchema,
|
||||
idSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -262,7 +267,7 @@ export class CollabMcp {
|
||||
tripId: idSchema,
|
||||
title: collabLinkCreateRequestSchema.shape.title.describe('What the link is, as the list shows it'),
|
||||
url: collabLinkCreateRequestSchema.shape.url.describe('An http(s) URL'),
|
||||
pinned: z.boolean().optional().describe('Pin the link to the top of the list'),
|
||||
pinned: collabLinkPinnedSchema.optional().describe('Pin the link to the top of the list'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: collabLinksOn,
|
||||
@@ -287,7 +292,7 @@ export class CollabMcp {
|
||||
linkId: idSchema,
|
||||
title: collabLinkUpdateRequestSchema.shape.title.describe('What the link is, as the list shows it'),
|
||||
url: collabLinkUpdateRequestSchema.shape.url.describe('An http(s) URL'),
|
||||
pinned: z.boolean().optional().describe('Pin the link to the top of the list, or false to unpin it'),
|
||||
pinned: collabLinkPinnedSchema.optional().describe('Pin the link to the top of the list, or false to unpin it'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: collabLinksOn,
|
||||
|
||||
@@ -88,6 +88,9 @@ export const MANAGED_LOCKED_SETTING_KEYS = [
|
||||
'llm_provider',
|
||||
'mapbox_access_token',
|
||||
'maps_api_key',
|
||||
// Whether the login page waits or goes straight to the provider is part of the
|
||||
// operator's single sign-on, like oidc_login itself (#2925).
|
||||
'oidc_auto_redirect',
|
||||
'oidc_login',
|
||||
'oidc_registration',
|
||||
'openweather_api_key',
|
||||
|
||||
@@ -65,6 +65,7 @@ export const PLUGIN_ENTITY_CONTRACT = {
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'reminder_sent_for',
|
||||
'costs_mode',
|
||||
],
|
||||
// The sole credential of the anonymous calendar feed.
|
||||
withheld: ['feed_token'],
|
||||
|
||||
@@ -15,29 +15,14 @@ import {
|
||||
settingsBulkRequestSchema,
|
||||
weekStartSchema,
|
||||
dateFormatSchema,
|
||||
dashboardTimezonesSchema,
|
||||
MAX_DASHBOARD_TIMEZONES,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Cap on the dashboard's world clocks. Far above what a person keeps on the
|
||||
* widget, but it stops a model from parking hundreds of zones in one row.
|
||||
*/
|
||||
export const MAX_DASHBOARD_TIMEZONES = 24;
|
||||
|
||||
/**
|
||||
* Whether the runtime knows the zone. The same check as the client's
|
||||
* isValidTimeZone: a clock in an unknown zone throws a RangeError while it
|
||||
* renders, and the widget would quietly drop it.
|
||||
*/
|
||||
function isKnownTimeZone(zone: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: zone });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Re-exported for the tool's tests, which hold the cap the description names.
|
||||
export { MAX_DASHBOARD_TIMEZONES };
|
||||
|
||||
/**
|
||||
* The only settings keys this surface may read or write.
|
||||
@@ -101,14 +86,7 @@ const DISPLAY_PREFERENCES = {
|
||||
optimize_from_accommodation: z.boolean(),
|
||||
// The dashboard world clocks (#3044). [] is a valid choice and shows none;
|
||||
// leaving the key unset keeps the widget's own fallback list.
|
||||
dashboard_timezones: z
|
||||
.array(
|
||||
z.string().min(1).max(64).refine(isKnownTimeZone, {
|
||||
message: 'Expected IANA time zone ids such as Europe/Madrid',
|
||||
}),
|
||||
)
|
||||
.max(MAX_DASHBOARD_TIMEZONES, `Expected at most ${MAX_DASHBOARD_TIMEZONES} time zones`)
|
||||
.refine((zones) => new Set(zones).size === zones.length, { message: 'Expected each time zone only once' }),
|
||||
dashboard_timezones: dashboardTimezonesSchema,
|
||||
} satisfies Record<string, z.ZodType>;
|
||||
|
||||
type DisplayPreferenceKey = keyof typeof DISPLAY_PREFERENCES;
|
||||
|
||||
@@ -29,7 +29,13 @@ import { TripReadModelService } from '../trip-read-model/trip-read-model.service
|
||||
import { TripWritesService, type TripListWriter } from './trip-writes.service';
|
||||
import { tripUpdatePermissions } from './trips.helpers';
|
||||
import { TripsService, NotFoundError, ValidationError } from './trips.service';
|
||||
import { idSchema, MAX_TRIP_DAYS, tripUpdateRequestSchema, type TripCostsMode } from '@trek/shared';
|
||||
import {
|
||||
idSchema,
|
||||
MAX_TRIP_DAYS,
|
||||
tripCalendarDayEventsSchema,
|
||||
tripUpdateRequestSchema,
|
||||
type TripCostsMode,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -691,8 +697,7 @@ export class TripsMcp {
|
||||
"Export a trip's itinerary and reservations as iCalendar (.ics) format text. Useful for importing into calendar apps.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
dayEvents: z
|
||||
.boolean()
|
||||
dayEvents: tripCalendarDayEventsSchema
|
||||
.optional()
|
||||
.describe(
|
||||
'false leaves out the all-day summary each day with untimed places or notes gets ("Day 1", ...), the same as days=0 on the download; the trip itself, timed stops and bookings stay. Default true.',
|
||||
|
||||
@@ -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);
|
||||
@@ -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`);
|
||||
@@ -283,7 +290,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?days=0`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -313,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);
|
||||
@@ -333,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);
|
||||
@@ -348,7 +355,7 @@ describe('Calendar-feed e2e (real auth guard + temp SQLite)', () => {
|
||||
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 = 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?days=0`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -380,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);');
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -253,14 +256,14 @@ describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
||||
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' });
|
||||
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');
|
||||
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 () => {
|
||||
|
||||
@@ -1,328 +0,0 @@
|
||||
/**
|
||||
* Unit tests for the collab link tools (#3076): list_collab_links,
|
||||
* create_collab_link, update_collab_link and delete_collab_link (CollabMcp).
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { CollabLinks } from '../../../src/db/entities/CollabLinks.entity';
|
||||
import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';
|
||||
import { addTripMember, createTrip, createUser } from '../../helpers/factories';
|
||||
import { countRows, findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { setAppSetting } from '../../helpers/factories/settings';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
|
||||
import { resetTestDb, setAddonEnabled, setCollabFeature } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
|
||||
const realtime = new FakeRealtimeService();
|
||||
const broadcastMock = realtime.broadcastMock;
|
||||
|
||||
beforeEach(async () => {
|
||||
resetTestDb(testDb);
|
||||
setAddonEnabled(testDb, ADDON_IDS.COLLAB, true);
|
||||
broadcastMock.mockClear();
|
||||
delete process.env.DEMO_MODE;
|
||||
// resetTestDb truncates app_settings, but the permission cache is module-scoped
|
||||
// and would keep serving whatever the previous case configured.
|
||||
await invalidatePermissionsCache();
|
||||
});
|
||||
|
||||
let orm: TestOrm;
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(testDb);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await orm.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
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);
|
||||
for (const args of [
|
||||
{ title: 'Script', url: 'javascript:alert(1)' },
|
||||
{ title: 'Mail', url: 'mailto:someone@example.com' },
|
||||
{ title: ' ', url: 'https://example.com' },
|
||||
]) {
|
||||
expect((await call(user.id, 'create_collab_link', { tripId: trip.id, ...args })).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([]);
|
||||
});
|
||||
});
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1017,9 +1017,11 @@ describe('Tool: list_collection_places', () => {
|
||||
}
|
||||
|
||||
async function seedPlaces(colId: number, ownerId: number, count: number): Promise<number[]> {
|
||||
const ids: number[] = [];
|
||||
for (let i = 1; i <= count; i++) ids.push(await seedPlace(colId, ownerId, `Spot ${i}`));
|
||||
return ids;
|
||||
// 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 () => {
|
||||
@@ -1067,8 +1069,8 @@ describe('Tool: list_collection_places', () => {
|
||||
await withHarness(user.id, async (h) => {
|
||||
const seen: unknown[] = [];
|
||||
const totals: number[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
// 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));
|
||||
@@ -1077,8 +1079,9 @@ describe('Tool: list_collection_places', () => {
|
||||
arguments: { label_ids: [done], place_ids: page.places.map((p) => p.id) },
|
||||
});
|
||||
expect(labelled.isError).toBeFalsy();
|
||||
cursor = page.next_cursor;
|
||||
} while (cursor);
|
||||
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]);
|
||||
|
||||
@@ -13,7 +13,7 @@ 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, createDay, createDayNote } 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 { setAppSetting } from '../../helpers/factories/settings';
|
||||
@@ -495,7 +495,10 @@ 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' });
|
||||
const day = createDay(testDb, trip.id, { date: '2025-06-01', day_number: 1 });
|
||||
// A dated trip comes with its days; the first one is the 1st of June.
|
||||
const day = testDb.prepare('SELECT id FROM days WHERE trip_id = ? AND day_number = 1').get(trip.id) as {
|
||||
id: number;
|
||||
};
|
||||
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>) =>
|
||||
|
||||
@@ -1686,7 +1686,8 @@ 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' });
|
||||
const day = createDay(testDb, trip.id, { date: '2025-06-02', day_number: 1 });
|
||||
// A dated trip comes with its days; the first one is the 2nd of June.
|
||||
const day = testDb.prepare('SELECT id FROM days WHERE trip_id = ? AND day_number = 1').get(trip.id) as { id: number };
|
||||
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' });
|
||||
|
||||
@@ -65,6 +65,7 @@ describe('managed key assignment', () => {
|
||||
'llm_provider',
|
||||
'mapbox_access_token',
|
||||
'maps_api_key',
|
||||
'oidc_auto_redirect',
|
||||
'oidc_login',
|
||||
'oidc_registration',
|
||||
'openweather_api_key',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { TRIP_PERMISSION_KEY } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import type { PlacesKmlService } from '../../../src/nest/places/places-kml.service';
|
||||
import { PlacesController } from '../../../src/nest/places/places.controller';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
@@ -25,6 +26,8 @@ vi.mock('../../../src/db/database', () => ({
|
||||
}));
|
||||
|
||||
const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as StorageService;
|
||||
// The KML export has its own service test; these handlers never reach it.
|
||||
const kmlStub = {} as PlacesKmlService;
|
||||
|
||||
const user = { id: 1, role: 'user', email: 'u@example.test' } as User;
|
||||
const trip = { user_id: 1 };
|
||||
@@ -70,13 +73,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('GET / lists with filters', async () => {
|
||||
const list = vi.fn().mockReturnValue([{ id: 1 }]);
|
||||
expect(
|
||||
await new PlacesController(svc({ list } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).list(
|
||||
user,
|
||||
'5',
|
||||
'beach',
|
||||
'cat',
|
||||
'tag',
|
||||
),
|
||||
await new PlacesController(
|
||||
svc({ list } as Partial<PlacesService>),
|
||||
new RuntimeEnvService(),
|
||||
storageStub,
|
||||
kmlStub,
|
||||
).list(user, '5', 'beach', 'cat', 'tag'),
|
||||
).toEqual({ places: [{ id: 1 }] });
|
||||
expect(list).toHaveBeenCalledWith('5', { search: 'beach', category: 'cat', tag: 'tag' });
|
||||
});
|
||||
@@ -86,7 +88,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const canEdit = vi.fn().mockReturnValue(false); // would 403 if reached
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).create(user, '5', {
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub, kmlStub).create(user, '5', {
|
||||
name: 'x'.repeat(201),
|
||||
}),
|
||||
),
|
||||
@@ -115,7 +117,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const onCreated = vi.fn();
|
||||
const s = svc({ create, broadcast, onCreated } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).create(user, '5', { name: 'Spot' }, 'sock'),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).create(
|
||||
user,
|
||||
'5',
|
||||
{ name: 'Spot' },
|
||||
'sock',
|
||||
),
|
||||
).toEqual({ place: { id: 9 } });
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'place:created', { place: { id: 9 } }, 'sock');
|
||||
expect(onCreated).toHaveBeenCalledWith('5', 9);
|
||||
@@ -127,14 +134,19 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('400 without a file', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).importGpx(user, '5', undefined, {}),
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).importGpx(
|
||||
user,
|
||||
'5',
|
||||
undefined,
|
||||
{},
|
||||
),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'No file uploaded' } });
|
||||
});
|
||||
it('400 when all import types are disabled', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).importGpx(user, '5', file, {
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).importGpx(user, '5', file, {
|
||||
importWaypoints: 'false',
|
||||
importRoutes: 'false',
|
||||
importTracks: 'false',
|
||||
@@ -166,7 +178,13 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
broadcast,
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importGpx(user, '5', file, {}, 'sock'),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGpx(
|
||||
user,
|
||||
'5',
|
||||
file,
|
||||
{},
|
||||
'sock',
|
||||
),
|
||||
).toEqual({ places: [{ id: 1 }, { id: 2 }], count: 2, skipped: 0 });
|
||||
expect(broadcast).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
@@ -182,7 +200,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
broadcast: vi.fn(),
|
||||
enrichImportedFilePlaces,
|
||||
} as Partial<PlacesService>);
|
||||
const c = new PlacesController(s, new RuntimeEnvService(), storageStub);
|
||||
const c = new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub);
|
||||
await c.importGpx(user, '5', file, {});
|
||||
expect(enrichImportedFilePlaces).not.toHaveBeenCalled();
|
||||
await c.importGpx(user, '5', file, { enrich: 'true' });
|
||||
@@ -199,7 +217,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('400 without a file', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).importMap(user, '5', undefined, {}),
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).importMap(
|
||||
user,
|
||||
'5',
|
||||
undefined,
|
||||
{},
|
||||
),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'No file uploaded' } });
|
||||
});
|
||||
@@ -208,7 +231,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ canEdit: vi.fn().mockReturnValue(false), importMapFile } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
),
|
||||
).toEqual({ status: 403, body: { error: 'No permission' } });
|
||||
expect(importMapFile).not.toHaveBeenCalled();
|
||||
@@ -216,7 +239,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('400 when both import types are disabled', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).importMap(user, '5', file, {
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {
|
||||
importPoints: 'false',
|
||||
importPaths: 'false',
|
||||
}),
|
||||
@@ -231,7 +254,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ importMapFile: vi.fn().mockResolvedValue({ places: [], summary }) } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
),
|
||||
).toEqual({
|
||||
status: 400,
|
||||
@@ -243,7 +266,13 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const result = { places: [{ id: 1 }, { id: 2 }], summary: { totalPlacemarks: 2 }, count: 2 };
|
||||
const s = svc({ importMapFile: vi.fn().mockResolvedValue(result), broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}, 'sock'),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(
|
||||
user,
|
||||
'5',
|
||||
file,
|
||||
{},
|
||||
'sock',
|
||||
),
|
||||
).toEqual(result);
|
||||
expect(broadcast).toHaveBeenCalledTimes(2);
|
||||
expect(broadcast).toHaveBeenCalledWith('5', 'place:created', { place: { id: 1 } }, 'sock');
|
||||
@@ -252,14 +281,14 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const result = { places: [{ id: 7 }] };
|
||||
const s = svc({ importMapFile: vi.fn().mockResolvedValue(result), broadcast: vi.fn() } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
).toEqual(result);
|
||||
});
|
||||
it('wraps a thrown Error from the service in a 400 with its message', async () => {
|
||||
const s = svc({ importMapFile: vi.fn().mockRejectedValue(new Error('bad kml')) } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'bad kml' } });
|
||||
});
|
||||
@@ -267,7 +296,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ importMapFile: vi.fn().mockRejectedValue('boom') } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'Failed to import map file' } });
|
||||
});
|
||||
@@ -277,7 +306,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importMap(user, '5', file, {}),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importMap(user, '5', file, {}),
|
||||
),
|
||||
).toEqual({ status: 418, body: { error: 'teapot' } });
|
||||
});
|
||||
@@ -292,7 +321,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({
|
||||
exportGpx: vi.fn().mockReturnValue({ gpx: '<gpx/>', filename: 'Alpine-week.gpx' }),
|
||||
} as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).exportGpx(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).exportGpx(
|
||||
user,
|
||||
'5',
|
||||
exportQuery,
|
||||
@@ -307,7 +336,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({
|
||||
exportGpx: vi.fn().mockReturnValue({ gpx: '<gpx/>', filename: '沖縄-4泊5日.gpx' }),
|
||||
} as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).exportGpx(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).exportGpx(
|
||||
user,
|
||||
'5',
|
||||
exportQuery,
|
||||
@@ -330,7 +359,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importGoogle(user, '5', { url: 'http://x' }),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGoogle(user, '5', {
|
||||
url: 'http://x',
|
||||
}),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'List is empty' } });
|
||||
});
|
||||
@@ -340,7 +371,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
broadcast: vi.fn(),
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importNaver(user, '5', { url: 'http://x' }),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importNaver(user, '5', {
|
||||
url: 'http://x',
|
||||
}),
|
||||
).toEqual({ places: [{ id: 1 }], count: 1, listName: 'Trip', skipped: 2 });
|
||||
});
|
||||
it('forwards the enrich flag + userId and broadcasts each imported place', async () => {
|
||||
@@ -348,7 +381,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ importGoogleList, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importGoogle(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGoogle(
|
||||
user,
|
||||
'5',
|
||||
{ url: 'http://x', enrich: true },
|
||||
@@ -369,7 +402,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const url = 'https://www.google.com/maps/dir/Berlin/Dresden/Prague';
|
||||
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importGoogle(user, '5', { url }),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGoogle(user, '5', { url }),
|
||||
).toEqual({
|
||||
places: [{ id: 9 }],
|
||||
count: 1,
|
||||
@@ -389,7 +422,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const importGoogleList = vi.fn().mockResolvedValue({ places: [], listName: 'L', skipped: 0 });
|
||||
const s = svc({ importGoogleDirections, importGoogleList, broadcast: vi.fn() } as Partial<PlacesService>);
|
||||
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).importGoogle(user, '5', {
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGoogle(user, '5', {
|
||||
url: 'https://maps.app.goo.gl/abc',
|
||||
});
|
||||
expect(importGoogleList).toHaveBeenCalled();
|
||||
@@ -401,7 +434,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importGoogle(user, '5', { url: 'http://x' }),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importGoogle(user, '5', {
|
||||
url: 'http://x',
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
status: 400,
|
||||
@@ -412,7 +447,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ importNaverList: vi.fn().mockRejectedValue('weird') } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).importNaver(user, '5', { url: 'http://x' }),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).importNaver(user, '5', {
|
||||
url: 'http://x',
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
status: 400,
|
||||
@@ -441,7 +478,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ canEdit: vi.fn().mockReturnValue(false), removeMany } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1] }),
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(user, '5', { ids: [1] }),
|
||||
),
|
||||
).toEqual({ status: 403, body: { error: 'No permission' } });
|
||||
expect(removeMany).not.toHaveBeenCalled();
|
||||
@@ -457,7 +494,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const scopedIds = vi.fn().mockReturnValue([1, 2]);
|
||||
const s = svc({ removeMany, onDeleted, broadcast, scopedIds } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(
|
||||
user,
|
||||
'5',
|
||||
{ ids: [1, 2] },
|
||||
@@ -477,7 +514,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const scopedIds = vi.fn().mockReturnValue([1]);
|
||||
const onDeleted = vi.fn();
|
||||
const s = svc({ removeMany, scopedIds, onDeleted, broadcast: vi.fn() } as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 99] });
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(user, '5', {
|
||||
ids: [1, 99],
|
||||
});
|
||||
expect(scopedIds).toHaveBeenCalledWith('5', [1, 99]);
|
||||
expect(onDeleted).toHaveBeenCalledTimes(1);
|
||||
expect(onDeleted).toHaveBeenCalledWith(1);
|
||||
@@ -505,7 +544,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
scopedIds: vi.fn().mockReturnValue([1]),
|
||||
broadcast: vi.fn(),
|
||||
} as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1] });
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(user, '5', { ids: [1] });
|
||||
expect(order).toEqual(['hook', 'delete']);
|
||||
});
|
||||
|
||||
@@ -517,7 +556,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const linkedExpenseIds = vi.fn().mockReturnValue([77]);
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ removeMany, linkedExpenseIds, broadcast } as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(
|
||||
user,
|
||||
'5',
|
||||
{ ids: [1, 2] },
|
||||
@@ -537,7 +576,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
.mockReturnValue({ deleted: [1], cancelled: { reservationIds: [12], budgetItemIds: [77] } });
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ removeMany, broadcast, scopedIds: vi.fn().mockReturnValue([1]) } as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1] }, 'sock');
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkDelete(
|
||||
user,
|
||||
'5',
|
||||
{ ids: [1] },
|
||||
'sock',
|
||||
);
|
||||
|
||||
// The place is the one change the tab made itself, so that echo stays
|
||||
// filtered. The booking and its expense went on the server alone.
|
||||
@@ -574,7 +618,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('400 when no patch field is present', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1] }),
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).bulkUpdate(user, '5', {
|
||||
ids: [1],
|
||||
}),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'Provide at least one field to update' } });
|
||||
});
|
||||
@@ -595,7 +641,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ updateMany, onUpdated, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkUpdate(
|
||||
user,
|
||||
'5',
|
||||
{ ids: [1, 2], category_id: 3 },
|
||||
@@ -610,7 +656,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const updateMany = vi.fn().mockReturnValue([{ id: 1 }]);
|
||||
const s = svc({ updateMany } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', {
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).bulkUpdate(user, '5', {
|
||||
ids: [1],
|
||||
category_id: null,
|
||||
}),
|
||||
@@ -630,7 +676,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
),
|
||||
).toEqual({ status: 404, body: { error: 'Place not found' } });
|
||||
const s = svc({ get: vi.fn().mockReturnValue({ id: 9 }) } as Partial<PlacesService>);
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).get(user, '5', '9')).toEqual({
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).get(user, '5', '9')).toEqual({
|
||||
place: { id: 9 },
|
||||
});
|
||||
});
|
||||
@@ -650,7 +696,13 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'X' }, 'sock'),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).update(
|
||||
user,
|
||||
'5',
|
||||
'9',
|
||||
{ name: 'X' },
|
||||
'sock',
|
||||
),
|
||||
).toEqual({ place: { id: 9 } });
|
||||
expect(onUpdated).toHaveBeenCalledWith(9);
|
||||
});
|
||||
@@ -661,28 +713,28 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const err = { status: 400, body: { error: 'route_color must be a hex colour like #4f46e5' } };
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', {
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub, kmlStub).update(user, '5', '9', {
|
||||
route_color: 'red',
|
||||
}),
|
||||
),
|
||||
).toEqual(err);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', {
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub, kmlStub).update(user, '5', '9', {
|
||||
route_color: '#12345',
|
||||
}),
|
||||
),
|
||||
).toEqual(err);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', {
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub, kmlStub).update(user, '5', '9', {
|
||||
route_color: 123,
|
||||
}),
|
||||
),
|
||||
).toEqual(err);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).create(user, '5', {
|
||||
new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub, kmlStub).create(user, '5', {
|
||||
name: 'T',
|
||||
route_color: 'red',
|
||||
}),
|
||||
@@ -696,7 +748,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ update, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).update(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).update(
|
||||
user,
|
||||
'5',
|
||||
'9',
|
||||
@@ -745,7 +797,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
};
|
||||
const siteErr = { status: 400, body: { error: 'website must be an http or https URL' } };
|
||||
const ctl = (over: Partial<PlacesService> = {}) =>
|
||||
new PlacesController(svc(over), new RuntimeEnvService(), storageStub);
|
||||
new PlacesController(svc(over), new RuntimeEnvService(), storageStub, kmlStub);
|
||||
|
||||
it('400s an image_url the marker builders were never meant to receive, before the permission check', async () => {
|
||||
const canEdit = vi.fn().mockReturnValue(false); // would 403 if it got that far
|
||||
@@ -827,7 +879,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub).update(
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).update(
|
||||
user,
|
||||
'5',
|
||||
'9',
|
||||
@@ -867,10 +919,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
}),
|
||||
broadcast: vi.fn(),
|
||||
} as Partial<PlacesService>);
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9')).toEqual({
|
||||
success: true,
|
||||
tourPlaceIds: [9],
|
||||
});
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).remove(user, '5', '9')).toEqual(
|
||||
{
|
||||
success: true,
|
||||
tourPlaceIds: [9],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('requires place_edit for single Place/Tour deletion', () => {
|
||||
@@ -893,7 +947,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
return { deleted: true, deletedTourPlaceIds: [], cancelled: { reservationIds: [], budgetItemIds: [] } };
|
||||
});
|
||||
const s = svc({ remove, onDeleted, broadcast: vi.fn() } as Partial<PlacesService>);
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9');
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).remove(user, '5', '9');
|
||||
expect(order).toEqual(['hook', 'delete']);
|
||||
});
|
||||
|
||||
@@ -904,7 +958,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const remove = vi.fn().mockReturnValue({ deleted: true, cancelled: { reservationIds: [12], budgetItemIds: [77] } });
|
||||
const s = svc({ remove, broadcast, linkedExpenseIds: vi.fn().mockReturnValue([]) } as Partial<PlacesService>);
|
||||
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9', 'sock');
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).remove(user, '5', '9', 'sock');
|
||||
|
||||
// The place echo stays filtered by the socket id; the booking and the
|
||||
// expense are sent to the deleting tab as well, because that tab only
|
||||
@@ -923,7 +977,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const remove = vi.fn();
|
||||
const s = svc({ get: vi.fn().mockReturnValue(null), onDeleted, remove } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() => new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '99')),
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).remove(user, '5', '99'),
|
||||
),
|
||||
).toEqual({ status: 404, body: { error: 'Place not found' } });
|
||||
expect(onDeleted).not.toHaveBeenCalled();
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
@@ -931,25 +987,31 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
|
||||
it('GET /:id/image maps service error + returns photos', async () => {
|
||||
const s = svc({ searchImage: vi.fn().mockResolvedValue({ photos: [{ url: 'x' }] }) } as Partial<PlacesService>);
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).image(user, '5', '9')).toEqual({
|
||||
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).image(user, '5', '9')).toEqual({
|
||||
photos: [{ url: 'x' }],
|
||||
});
|
||||
const e = svc({ searchImage: vi.fn().mockRejectedValue(new DomainError(400, 'No key')) } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() => new PlacesController(e, new RuntimeEnvService(), storageStub).image(user, '5', '9')),
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(e, new RuntimeEnvService(), storageStub, kmlStub).image(user, '5', '9'),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'No key' } });
|
||||
});
|
||||
|
||||
it('GET /:id/image turns an unexpected throw into a 500, but re-throws an HttpException as-is', async () => {
|
||||
const boom = svc({ searchImage: vi.fn().mockRejectedValue(new Error('Unsplash down')) } as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() => new PlacesController(boom, new RuntimeEnvService(), storageStub).image(user, '5', '9')),
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(boom, new RuntimeEnvService(), storageStub, kmlStub).image(user, '5', '9'),
|
||||
),
|
||||
).toEqual({ status: 500, body: { error: 'Error searching for image' } });
|
||||
const http = svc({
|
||||
searchImage: vi.fn().mockRejectedValue(new HttpException({ error: 'rate limited' }, 429)),
|
||||
} as Partial<PlacesService>);
|
||||
expect(
|
||||
await thrownAsync(() => new PlacesController(http, new RuntimeEnvService(), storageStub).image(user, '5', '9')),
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(http, new RuntimeEnvService(), storageStub, kmlStub).image(user, '5', '9'),
|
||||
),
|
||||
).toEqual({ status: 429, body: { error: 'rate limited' } });
|
||||
});
|
||||
|
||||
@@ -980,7 +1042,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
it('400 when no file was uploaded', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).uploadImage(user, '5', '9', undefined),
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).uploadImage(
|
||||
user,
|
||||
'5',
|
||||
'9',
|
||||
undefined,
|
||||
),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'No image uploaded' } });
|
||||
});
|
||||
@@ -1003,7 +1070,13 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
const broadcast = vi.fn();
|
||||
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
|
||||
expect(
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub).uploadImage(user, '5', '9', file, 'sock'),
|
||||
await new PlacesController(s, new RuntimeEnvService(), storageStub, kmlStub).uploadImage(
|
||||
user,
|
||||
'5',
|
||||
'9',
|
||||
file,
|
||||
'sock',
|
||||
),
|
||||
).toEqual({ place: { id: 9 } });
|
||||
expect(storageStub.put).toHaveBeenCalledWith('places', 'abc.jpg', { tmpPath: undefined });
|
||||
expect(update).toHaveBeenCalledWith('5', '9', { image_url: '/uploads/places/abc.jpg' });
|
||||
@@ -1018,7 +1091,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
|
||||
try {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub).uploadImage(demo, '5', '9', file),
|
||||
new PlacesController(svc(), new RuntimeEnvService(), storageStub, kmlStub).uploadImage(
|
||||
demo,
|
||||
'5',
|
||||
'9',
|
||||
file,
|
||||
),
|
||||
),
|
||||
).toEqual({
|
||||
status: 403,
|
||||
|
||||
@@ -38,6 +38,7 @@ const mcp = new PlacesMcp(
|
||||
guards as never,
|
||||
{} as never,
|
||||
origins as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
@@ -373,6 +373,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
guards as never,
|
||||
{} as never,
|
||||
{ recordImported: vi.fn(async () => undefined) } as never,
|
||||
{} as never,
|
||||
);
|
||||
const input = {
|
||||
tripId: 1,
|
||||
|
||||
@@ -20,6 +20,7 @@ import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { TripAccessGuard, TRIP_PERMISSION_KEY } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import type { PlacesKmlService } from '../../../src/nest/places/places-kml.service';
|
||||
import { PlacesController } from '../../../src/nest/places/places.controller';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
@@ -112,6 +113,7 @@ function placesFixture() {
|
||||
places as unknown as PlacesService,
|
||||
{} as RuntimeEnvService,
|
||||
{} as StorageService,
|
||||
{} as PlacesKmlService,
|
||||
);
|
||||
return { places, controller };
|
||||
}
|
||||
|
||||
@@ -228,3 +228,9 @@ export const collabLinkPreviewResponseSchema = z.object({
|
||||
url: z.string(),
|
||||
});
|
||||
export type CollabLinkPreviewResponse = z.infer<typeof collabLinkPreviewResponseSchema>;
|
||||
|
||||
/**
|
||||
* Pinning a link from an MCP tool: a plain boolean. The REST bodies also take
|
||||
* the stored 1 or 0 (`pinned` above); a tool's caller says true or false.
|
||||
*/
|
||||
export const collabLinkPinnedSchema = z.boolean();
|
||||
|
||||
@@ -20,7 +20,7 @@ const toursModules = import.meta.glob<{ default: TranslationStrings }>('./*/tour
|
||||
const TOUR_DOMAINS: { file: string; generalKeyCount: number; modules: DomainModules }[] = [
|
||||
{
|
||||
file: 'tours',
|
||||
generalKeyCount: 1359,
|
||||
generalKeyCount: 1361,
|
||||
modules: toursModules,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
PLANNER_TRIP_VIEWS_MAX,
|
||||
compactPlannerTripViews,
|
||||
plannerTripViewsSchema,
|
||||
dashboardTimezonesSchema,
|
||||
MAX_DASHBOARD_TIMEZONES,
|
||||
} from './settings.schema';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
@@ -63,3 +65,17 @@ describe('compactPlannerTripViews', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('dashboardTimezonesSchema (#3044)', () => {
|
||||
it('takes known zones once each, up to the cap, and an empty list', () => {
|
||||
expect(dashboardTimezonesSchema.safeParse(['Europe/Madrid', 'Asia/Tokyo']).success).toBe(true);
|
||||
expect(dashboardTimezonesSchema.safeParse([]).success).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses an unknown zone, a repeated one and one past the cap', () => {
|
||||
expect(dashboardTimezonesSchema.safeParse(['Mars/Olympus']).success).toBe(false);
|
||||
expect(dashboardTimezonesSchema.safeParse(['Europe/Madrid', 'Europe/Madrid']).success).toBe(false);
|
||||
const tooMany = Intl.supportedValuesOf('timeZone').slice(0, MAX_DASHBOARD_TIMEZONES + 1);
|
||||
expect(dashboardTimezonesSchema.safeParse(tooMany).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -127,3 +127,33 @@ export function compactPlannerTripViews(views: PlannerTripViews): PlannerTripVie
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cap on the dashboard's world clocks (#3044). Far above what a person keeps on
|
||||
* the widget, but it stops a model from parking hundreds of zones in one row.
|
||||
*/
|
||||
export const MAX_DASHBOARD_TIMEZONES = 24;
|
||||
|
||||
/**
|
||||
* Whether the runtime knows the zone. The same check as the client's
|
||||
* isValidTimeZone: a clock in an unknown zone throws a RangeError while it
|
||||
* renders, and the widget would quietly drop it.
|
||||
*/
|
||||
function isKnownTimeZone(zone: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: zone });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The dashboard world clocks as IANA zone ids, each once; [] shows none. */
|
||||
export const dashboardTimezonesSchema = z
|
||||
.array(
|
||||
z.string().min(1).max(64).refine(isKnownTimeZone, {
|
||||
message: 'Expected IANA time zone ids such as Europe/Madrid',
|
||||
}),
|
||||
)
|
||||
.max(MAX_DASHBOARD_TIMEZONES, `Expected at most ${MAX_DASHBOARD_TIMEZONES} time zones`)
|
||||
.refine((zones) => new Set(zones).size === zones.length, { message: 'Expected each time zone only once' });
|
||||
|
||||
@@ -206,3 +206,9 @@ export const tripCalendarQuerySchema = z.object({
|
||||
days: z.enum(['0', '1']).optional(),
|
||||
});
|
||||
export type TripCalendarQuery = z.infer<typeof tripCalendarQuerySchema>;
|
||||
|
||||
/**
|
||||
* The MCP export's switch for the per-day summary events (#2602): what the
|
||||
* routes' `days` query says as 0 or 1, as a boolean for a tool's caller.
|
||||
*/
|
||||
export const tripCalendarDayEventsSchema = z.boolean();
|
||||
|
||||
Reference in New Issue
Block a user