mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
feat(journey): create draft entries from gallery photos
Groups the gallery photos on no entry by local day, then by time gap and distance, names each group through the geocoder (capped per preview, with the country or the day as fallback) and writes the groups the traveller keeps as draft entries with their photos in one transaction. Photos put on an entry meanwhile or named twice are left out and reported; existing entries are never touched. REST routes under /api/journeys/:id/entries/from-photos and the MCP tools preview_journey_entries_from_photos and create_journey_entries_from_photos share one service and the journey edit right (#1920).
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920), end to
|
||||
* end: the whole app (buildApp, the real AddonGuard, JwtAuthGuard, Zod pipe
|
||||
* and response contracts, the real MCP registry with its addon gate and error
|
||||
* mapper) on a migrated temp database. The geocoder is the one thing
|
||||
* replaced, so no test asks a network for a place name; the broadcasts are
|
||||
* spied on the container's realtime service.
|
||||
*
|
||||
* The walk: the routes are behind the addon and the session; an editor
|
||||
* previews the gallery's photos as groups and writes two of them as drafts
|
||||
* with their photos; sending the same create again writes nothing twice; a
|
||||
* viewer and a malformed body are refused; the MCP tools answer what REST
|
||||
* answers.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { JourneyEntries } from '../../src/db/entities/JourneyEntries.entity';
|
||||
import { JourneyEntryPhotos } from '../../src/db/entities/JourneyEntryPhotos.entity';
|
||||
import { JourneyPhotos } from '../../src/db/entities/JourneyPhotos.entity';
|
||||
import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';
|
||||
import { countRows, findRows, insertRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { spyOnRealtime } from '../helpers/fake-realtime';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
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 request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let realtime: ReturnType<typeof spyOnRealtime>;
|
||||
|
||||
const VENICE = { lat: 45.4341, lng: 12.3388 };
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
realtime = spyOnRealtime(app);
|
||||
vi.spyOn(app.get(MapsService), 'reverseGeocode').mockResolvedValue({ name: 'Venezia', address: null });
|
||||
}, 60_000);
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetRateLimits(app);
|
||||
await setAddonEnabled(orm, 'journey', true);
|
||||
realtime.broadcastToUser.mockClear();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
async function scene() {
|
||||
const { user: owner } = await makeUser(orm);
|
||||
const { user: editor } = await makeUser(orm);
|
||||
const { user: viewer } = await makeUser(orm);
|
||||
const journey = await makeJourney(orm, owner.id, { title: 'Venice' });
|
||||
await addJourneyContributor(orm, journey.id, editor.id, 'editor');
|
||||
await addJourneyContributor(orm, journey.id, viewer.id, 'viewer');
|
||||
const photo = async (takenAt: string | null, where: { lat: number; lng: number } | null = VENICE) => {
|
||||
const photoId = await insertRow(orm, TrekPhotos, {
|
||||
provider: 'local',
|
||||
owner: owner.id,
|
||||
file_path: 'journey/p.jpg',
|
||||
taken_at: takenAt,
|
||||
lat: where?.lat ?? null,
|
||||
lng: where?.lng ?? null,
|
||||
});
|
||||
return insertRow(orm, JourneyPhotos, { journey: journey.id, photo: photoId, sort_order: 0, created_at: 0 });
|
||||
};
|
||||
const morning = await photo('2026-05-14T07:00:00Z');
|
||||
const later = await photo('2026-05-14T08:00:00Z', null);
|
||||
const nextDay = await photo('2026-05-15T07:00:00Z');
|
||||
await photo(null);
|
||||
return { owner, editor, viewer, journey, morning, later, nextDay };
|
||||
}
|
||||
|
||||
const base = (journeyId: number) => `/api/journeys/${journeyId}/entries/from-photos`;
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
|
||||
/** One MCP tool call on the real registry as `userId`: its JSON, or its error text. */
|
||||
async function callTool(userId: number, name: string, args: Record<string, unknown>) {
|
||||
const server = createLocalMcpServer('TREK journey from photos e2e');
|
||||
const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);
|
||||
await withRequestContext(orm, () =>
|
||||
app
|
||||
.get(McpRegistryService)
|
||||
.attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
|
||||
);
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'journey-from-photos-e2e', version: '1.0.0' });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
try {
|
||||
const result = await client.callTool({ name, arguments: args });
|
||||
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
|
||||
const text = content[0]?.text ?? '';
|
||||
return result.isError === true ? { error: text } : (JSON.parse(text) as Record<string, unknown>);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('journey entries from photos e2e', () => {
|
||||
it('JRNPHOTOS-E2E-001: answers 404 with the Journey addon off before asking who the caller is, and 401 without a session', async () => {
|
||||
const s = await scene();
|
||||
await setAddonEnabled(orm, 'journey', false);
|
||||
expect(
|
||||
(
|
||||
await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.send({})
|
||||
).status,
|
||||
).toBe(404);
|
||||
await setAddonEnabled(orm, 'journey', true);
|
||||
expect(
|
||||
(
|
||||
await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.send({})
|
||||
).status,
|
||||
).toBe(401);
|
||||
expect((await request(app.getHttpServer()).post(base(s.journey.id)).send({ groups: [] })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('JRNPHOTOS-E2E-002: an editor previews the groups and writes them as drafts with their photos, announced to the journey', async () => {
|
||||
const s = await scene();
|
||||
|
||||
const preview = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(s.editor.id))
|
||||
.send({ timezone: 'Europe/Rome', lang: 'it' });
|
||||
expect(preview.status).toBe(200);
|
||||
expect(preview.body).toMatchObject({ withoutCaptureTime: 1, maxGapMinutes: 180, maxDistanceKm: 20 });
|
||||
const clusters = preview.body.clusters as Array<{ photoIds: number[]; suggestedTitle: string; date: string }>;
|
||||
expect(clusters.map((c) => [c.date, c.photoIds, c.suggestedTitle])).toEqual([
|
||||
['2026-05-14', [s.morning, s.later], 'Venezia'],
|
||||
['2026-05-15', [s.nextDay], 'Venezia'],
|
||||
]);
|
||||
expect(await countRows(orm, JourneyEntries, { journey: s.journey.id })).toBe(0);
|
||||
|
||||
const created = await request(app.getHttpServer())
|
||||
.post(base(s.journey.id))
|
||||
.set(as(s.editor.id))
|
||||
.set('X-Socket-Id', '11')
|
||||
.send({
|
||||
timezone: 'Europe/Rome',
|
||||
groups: [
|
||||
{ photoIds: clusters[0]?.photoIds, title: 'San Marco', locationName: 'Venezia' },
|
||||
{ photoIds: clusters[1]?.photoIds, title: clusters[1]?.suggestedTitle },
|
||||
],
|
||||
});
|
||||
|
||||
expect(created.status).toBe(200);
|
||||
expect(created.body).toEqual({
|
||||
entries: [
|
||||
{ id: expect.any(Number), title: 'San Marco', entry_date: '2026-05-14', entry_time: '09:00', photoCount: 2 },
|
||||
{ id: expect.any(Number), title: 'Venezia', entry_date: '2026-05-15', entry_time: '09:00', photoCount: 1 },
|
||||
],
|
||||
skippedPhotoIds: [],
|
||||
});
|
||||
const entries = await findRows(orm, JourneyEntries, { journey: s.journey.id });
|
||||
expect(entries).toHaveLength(2);
|
||||
for (const entry of entries) expect(entry).toMatchObject({ is_draft: 1, author_id: s.editor.id });
|
||||
expect(await countRows(orm, JourneyEntryPhotos)).toBeGreaterThanOrEqual(3);
|
||||
expect(realtime.broadcastToUser).toHaveBeenCalledWith(
|
||||
s.viewer.id,
|
||||
expect.objectContaining({ type: 'journey:entry:created', journeyId: s.journey.id }),
|
||||
'11',
|
||||
);
|
||||
|
||||
// The same create again finds every photo on an entry and writes nothing twice.
|
||||
const again = await request(app.getHttpServer())
|
||||
.post(base(s.journey.id))
|
||||
.set(as(s.editor.id))
|
||||
.send({ groups: [{ photoIds: [s.morning, s.later] }] });
|
||||
expect(again.status).toBe(200);
|
||||
expect(again.body).toEqual({ entries: [], skippedPhotoIds: [s.morning, s.later] });
|
||||
expect(await countRows(orm, JourneyEntries, { journey: s.journey.id })).toBe(2);
|
||||
const previewAfter = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(s.owner.id))
|
||||
.send({});
|
||||
expect(previewAfter.body.clusters).toEqual([]);
|
||||
});
|
||||
|
||||
it('JRNPHOTOS-E2E-003: refuses a viewer, a stranger and a body the contract refuses, writing nothing', async () => {
|
||||
const s = await scene();
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const body = { groups: [{ photoIds: [s.morning] }] };
|
||||
|
||||
const viewer = await request(app.getHttpServer()).post(base(s.journey.id)).set(as(s.viewer.id)).send(body);
|
||||
expect(viewer.status).toBe(403);
|
||||
expect(viewer.body).toMatchObject({ error: 'Not allowed' });
|
||||
const strangerRes = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(stranger.id))
|
||||
.send({});
|
||||
expect(strangerRes.status).toBe(404);
|
||||
expect(strangerRes.body).toMatchObject({ error: 'Journey not found' });
|
||||
|
||||
for (const bad of [{}, { groups: [] }, { groups: [{ photoIds: ['1'] }] }, { groups: [{ photoIds: [1] }], x: 1 }]) {
|
||||
const res = await request(app.getHttpServer()).post(base(s.journey.id)).set(as(s.owner.id)).send(bad);
|
||||
expect(res.status, JSON.stringify(bad)).toBe(400);
|
||||
}
|
||||
const badZone = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(s.owner.id))
|
||||
.send({ timezone: 'Mars/Olympus' });
|
||||
expect(badZone.status).toBe(400);
|
||||
expect(await countRows(orm, JourneyEntries, { journey: s.journey.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('JRNPHOTOS-E2E-004: the MCP tools answer what REST answers and refuse a viewer the same way', async () => {
|
||||
const s = await scene();
|
||||
const viaRest = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(s.owner.id))
|
||||
.send({ lang: 'it' });
|
||||
const viaTool = await callTool(s.owner.id, 'preview_journey_entries_from_photos', {
|
||||
journeyId: s.journey.id,
|
||||
lang: 'it',
|
||||
});
|
||||
expect(viaTool).toEqual(viaRest.body);
|
||||
|
||||
const refused = await callTool(s.viewer.id, 'create_journey_entries_from_photos', {
|
||||
journeyId: s.journey.id,
|
||||
groups: [{ photoIds: [s.morning] }],
|
||||
});
|
||||
expect(refused).toEqual({ error: expect.stringContaining('Not allowed') });
|
||||
|
||||
const created = await callTool(s.owner.id, 'create_journey_entries_from_photos', {
|
||||
journeyId: s.journey.id,
|
||||
groups: [{ photoIds: [s.nextDay], title: 'Rialto' }],
|
||||
});
|
||||
expect(created).toEqual({
|
||||
entries: [
|
||||
{ id: expect.any(Number), title: 'Rialto', entry_date: '2026-05-15', entry_time: '09:00', photoCount: 1 },
|
||||
],
|
||||
skippedPhotoIds: [],
|
||||
});
|
||||
expect(await countRows(orm, JourneyEntries, { journey: s.journey.id })).toBe(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user