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:
Maurice
2026-11-30 14:32:40 +01:00
parent ebbd8c5362
commit 9c8a33d400
16 changed files with 2023 additions and 0 deletions
@@ -0,0 +1,110 @@
/**
* `JourneyPhotosRepository.listOffEntries` (#1920): the gallery photos of one
* journey that sit on no entry (a suggestion counts as an entry), with when
* and where they were taken; one without a capture time comes back with
* `taken_at` null, an empty capture time reads as null too.
*/
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 type { JourneyPhotosRepository } from '../../../../src/db/repositories/JourneyPhotos.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeJourney, makeJourneyEntry } from '../../../helpers/factories/journeys';
import { insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let photos: JourneyPhotosRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
photos = t.repo(JourneyPhotos);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function galleryPhoto(
journeyId: number,
ownerId: number,
over: Partial<{ taken_at: string; lat: number; lng: number; media_type: string }> = {},
): Promise<number> {
const photoId = await insertRow(t, TrekPhotos, {
provider: 'local',
owner: ownerId,
file_path: 'journey/p.jpg',
...over,
});
return insertRow(t, JourneyPhotos, { journey: journeyId, photo: photoId, sort_order: 0, created_at: Date.now() });
}
describe('JourneyPhotosRepository.listOffEntries', () => {
it('JPOFF-001: lists the journey photos on no entry with their capture time, position and kind, in gallery-row order', async () => {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
const other = await makeJourney(t, user.id);
const entry = await makeJourneyEntry(t, journey.id, user.id);
const suggestion = await makeJourneyEntry(t, journey.id, user.id, { type: 'skeleton' });
const free = await galleryPhoto(journey.id, user.id, { taken_at: '2026-05-14T07:00:00Z', lat: 45.43, lng: 12.33 });
const clip = await galleryPhoto(journey.id, user.id, {
taken_at: '2026-05-14T08:00:00+02:00',
media_type: 'video',
});
const untimed = await galleryPhoto(journey.id, user.id);
const blank = await galleryPhoto(journey.id, user.id, { taken_at: '' });
const onEntry = await galleryPhoto(journey.id, user.id, { taken_at: '2026-05-14T09:00:00Z' });
const onSuggestion = await galleryPhoto(journey.id, user.id, { taken_at: '2026-05-14T10:00:00Z' });
await galleryPhoto(other.id, user.id, { taken_at: '2026-05-14T11:00:00Z' });
await insertRow(t, JourneyEntryPhotos, { entry: entry.id, journeyPhoto: onEntry, sort_order: 0, created_at: 0 });
await insertRow(t, JourneyEntryPhotos, {
entry: suggestion.id,
journeyPhoto: onSuggestion,
sort_order: 0,
created_at: 0,
});
const rows = await photos.listOffEntries(journey.id);
expect(rows).toEqual([
{
id: free,
photo_id: expect.any(Number),
taken_at: '2026-05-14T07:00:00Z',
lat: 45.43,
lng: 12.33,
media_type: 'image',
},
{
id: clip,
photo_id: expect.any(Number),
taken_at: '2026-05-14T08:00:00+02:00',
lat: null,
lng: null,
media_type: 'video',
},
{ id: untimed, photo_id: expect.any(Number), taken_at: null, lat: null, lng: null, media_type: 'image' },
{ id: blank, photo_id: expect.any(Number), taken_at: null, lat: null, lng: null, media_type: 'image' },
]);
});
it('JPOFF-002: a journey without photos, or one whose photos are all on entries, lists none', async () => {
const { user } = await makeUser(t);
const journey = await makeJourney(t, user.id);
expect(await photos.listOffEntries(journey.id)).toEqual([]);
const entry = await makeJourneyEntry(t, journey.id, user.id);
const linked = await galleryPhoto(journey.id, user.id, { taken_at: '2026-05-14T07:00:00Z' });
await insertRow(t, JourneyEntryPhotos, { entry: entry.id, journeyPhoto: linked, sort_order: 0, created_at: 0 });
expect(await photos.listOffEntries(journey.id)).toEqual([]);
});
});
@@ -0,0 +1,64 @@
/**
* JourneyEntriesFromPhotosController (#1920): the routes of draft entries made
* from gallery photos, their guards and what they hand the service.
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
import { JourneyEntriesFromPhotosController } from '../../../../src/nest/journey/journey-entries-from-photos.controller';
import type { JourneyEntriesFromPhotosService } from '../../../../src/nest/journey/journey-entries-from-photos.service';
import type { User } from '../../../../src/types';
import { RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 4 } as User;
describe('JourneyEntriesFromPhotosController', () => {
it('JRNPHOTOS-CTL-001: sits behind the Journey addon before auth, both POSTs answering 200', () => {
expect(Reflect.getMetadata(PATH_METADATA, JourneyEntriesFromPhotosController)).toBe(
'api/journeys/:id/entries/from-photos',
);
expect(Reflect.getMetadata(GUARDS_METADATA, JourneyEntriesFromPhotosController)).toEqual([
AddonGuard,
JwtAuthGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, JourneyEntriesFromPhotosController)).toEqual({
addonId: 'journey',
label: 'Journey',
});
const routes = [
['preview', 'preview'],
['create', '/'],
] as const;
for (const [handler, path] of routes) {
const fn = JourneyEntriesFromPhotosController.prototype[handler];
expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(RequestMethod.POST);
expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(path);
expect(Reflect.getMetadata(HTTP_CODE_METADATA, fn)).toBe(200);
}
});
it('JRNPHOTOS-CTL-002: hands the caller, the journey, the body and the socket id to the service', async () => {
const service = {
preview: vi.fn(async () => ({ clusters: [], withoutCaptureTime: 0, maxGapMinutes: 180, maxDistanceKm: 20 })),
create: vi.fn(async () => ({ entries: [], skippedPhotoIds: [7] })),
};
const controller = new JourneyEntriesFromPhotosController(service as unknown as JourneyEntriesFromPhotosService);
expect(await controller.preview(user, 9, { lang: 'de' })).toEqual({
clusters: [],
withoutCaptureTime: 0,
maxGapMinutes: 180,
maxDistanceKm: 20,
});
expect(service.preview).toHaveBeenCalledExactlyOnceWith(4, 9, { lang: 'de' });
const body = { groups: [{ photoIds: [7], title: 'Rialto' }] };
expect(await controller.create(user, 9, body, 'sock-1')).toEqual({ entries: [], skippedPhotoIds: [7] });
expect(service.create).toHaveBeenCalledExactlyOnceWith(4, 9, body, 'sock-1');
});
});
@@ -0,0 +1,235 @@
/**
* The pure half of journal entries from gallery photos (#1920): the local
* clock each photo is read on, the groups a journey's photos fall into, what
* a group becomes and the title it gets without a place name.
*/
import {
carriedOffsetMinutes,
centroid,
clusterCaptures,
fallbackTitle,
intlLanguage,
isLocated,
localCaptures,
summarizeCluster,
type FromPhotosPhoto,
} from '../../../../src/nest/journey/journey-entries-from-photos.helpers';
import { describe, expect, it } from 'vitest';
const VENICE = { lat: 45.4341, lng: 12.3388 };
const MURANO = { lat: 45.4586, lng: 12.3536 };
const VERONA = { lat: 45.4384, lng: 10.9916 };
const TOKYO = { lat: 35.6812, lng: 139.7671 };
let nextId = 1;
function photo(takenAt: string, where: { lat: number; lng: number } | null, over: Partial<FromPhotosPhoto> = {}) {
return {
id: nextId++,
takenAt,
lat: where?.lat ?? null,
lng: where?.lng ?? null,
mediaType: 'image',
...over,
};
}
const THRESHOLDS = { maxGapMinutes: 180, maxDistanceKm: 20 };
const groups = (photos: FromPhotosPhoto[], fallback: string | null = null, thresholds = THRESHOLDS) =>
clusterCaptures(localCaptures(photos, fallback), thresholds).map((cluster) => cluster.map((c) => c.id));
describe('carriedOffsetMinutes', () => {
it('JRNPHOTOS-HELP-001: reads an offset after the clock time, never a Z, a date alone or an offset out of range', () => {
expect(carriedOffsetMinutes('2026-05-14T09:10:00+02:00')).toBe(120);
expect(carriedOffsetMinutes('2026-05-14T09:10:00.123-0530')).toBe(-330);
expect(carriedOffsetMinutes('2026-05-14T09:10+05:45')).toBe(345);
expect(carriedOffsetMinutes('2026-05-14T09:10:00Z')).toBeNull();
expect(carriedOffsetMinutes('2026-05-14T09:10:00')).toBeNull();
expect(carriedOffsetMinutes('2026-05-14')).toBeNull();
expect(carriedOffsetMinutes('2026-05-14T09:10:00+15:00')).toBeNull();
expect(carriedOffsetMinutes('2026-05-14T09:10:00+02:75')).toBeNull();
});
});
describe('isLocated', () => {
it('JRNPHOTOS-HELP-002: a position is a finite pair on the globe that is not 0,0', () => {
expect(isLocated(45.4, 12.3)).toBe(true);
expect(isLocated(0, 12.3)).toBe(true);
expect(isLocated(0, 0)).toBe(false);
expect(isLocated(null, 12.3)).toBe(false);
expect(isLocated(45.4, null)).toBe(false);
expect(isLocated(91, 12.3)).toBe(false);
expect(isLocated(45.4, 181)).toBe(false);
expect(isLocated(Number.NaN, 12.3)).toBe(false);
});
});
describe('localCaptures', () => {
it('JRNPHOTOS-HELP-003: the offset a capture time carries wins over the place it was taken', () => {
const [capture] = localCaptures([photo('2026-05-14T23:30:00+02:00', TOKYO)], 'America/New_York');
expect(capture).toMatchObject({ date: '2026-05-14', time: '23:30', zone: 'UTC+02:00', located: true });
const [west] = localCaptures([photo('2026-05-14T01:00:00-05:30', null)], null);
expect(west).toMatchObject({ date: '2026-05-14', time: '01:00', zone: 'UTC-05:30', located: false });
});
it('JRNPHOTOS-HELP-004: a UTC capture time is read in the zone of the place, across midnight', () => {
// 22:30 UTC is 07:30 the next morning in Tokyo.
const [capture] = localCaptures([photo('2026-05-14T22:30:00Z', TOKYO)], 'Europe/Berlin');
expect(capture).toMatchObject({ date: '2026-05-15', time: '07:30', zone: 'Asia/Tokyo' });
});
it('JRNPHOTOS-HELP-005: a photo without a position borrows the zone of the nearest geotagged one within three days', () => {
const near = photo('2026-05-15T12:00:00Z', null);
const far = photo('2026-05-25T22:00:00Z', null);
const captures = localCaptures(
[photo('2026-05-14T01:00:00Z', VENICE), photo('2026-05-15T23:00:00Z', TOKYO), near, far],
'America/New_York',
);
const byId = new Map(captures.map((c) => [c.id, c]));
// Nearer in time to the Tokyo photo than to the Venice one.
expect(byId.get(near.id)).toMatchObject({ zone: 'Asia/Tokyo', date: '2026-05-15', time: '21:00' });
// Eleven days from any geotagged photo: the caller's zone.
expect(byId.get(far.id)).toMatchObject({ zone: 'America/New_York', date: '2026-05-25', time: '18:00' });
});
it('JRNPHOTOS-HELP-006: without any zone to go on the day is read in UTC, and a time that does not parse is left out', () => {
const lost = photo('2026-05-14T23:30:00Z', null);
const captures = localCaptures(
[lost, photo('not a time', VENICE), photo('2026-05-14T10:00:00Z', { lat: 0, lng: 0 })],
null,
);
expect(captures).toHaveLength(2);
expect(captures[0]).toMatchObject({ id: lost.id, zone: 'UTC', date: '2026-05-14', time: '23:30' });
expect(captures[1]).toMatchObject({ zone: 'UTC', located: false });
});
it('JRNPHOTOS-HELP-007: an unknown fallback zone falls back to UTC instead of failing', () => {
const [capture] = localCaptures([photo('2026-05-14T23:30:00Z', null)], 'Mars/Olympus');
expect(capture).toMatchObject({ zone: 'UTC', date: '2026-05-14', time: '23:30' });
});
});
describe('clusterCaptures', () => {
it('JRNPHOTOS-HELP-008: photos of one place on one morning are one group, in the order they were taken', () => {
const a = photo('2026-05-14T08:10:00Z', VENICE);
const b = photo('2026-05-14T07:10:00Z', VENICE);
const c = photo('2026-05-14T09:40:00Z', MURANO);
expect(groups([a, b, c])).toEqual([[b.id, a.id, c.id]]);
});
it('JRNPHOTOS-HELP-009: the local midnight splits a group, even at the same place and minutes apart', () => {
// 21:50 and 22:10 UTC are 23:50 and 00:10 in Venice.
const late = photo('2026-05-14T21:50:00Z', VENICE);
const early = photo('2026-05-14T22:10:00Z', VENICE);
const captures = localCaptures([late, early], null);
expect(captures.map((c) => c.date)).toEqual(['2026-05-14', '2026-05-15']);
expect(groups([late, early])).toEqual([[late.id], [early.id]]);
});
it('JRNPHOTOS-HELP-010: a gap longer than the threshold starts a new group, a shorter one does not', () => {
const morning = photo('2026-05-14T07:00:00Z', VENICE);
const later = photo('2026-05-14T09:59:00Z', VENICE);
const evening = photo('2026-05-14T13:00:00Z', VENICE);
expect(groups([morning, later, evening])).toEqual([[morning.id, later.id], [evening.id]]);
expect(groups([morning, later, evening], null, { maxGapMinutes: 60, maxDistanceKm: 20 })).toEqual([
[morning.id],
[later.id],
[evening.id],
]);
});
it('JRNPHOTOS-HELP-011: a distance longer than the threshold starts a new group within the hour', () => {
const venice = photo('2026-05-14T07:00:00Z', VENICE);
const verona = photo('2026-05-14T07:45:00Z', VERONA);
expect(groups([venice, verona])).toEqual([[venice.id], [verona.id]]);
expect(groups([venice, verona], null, { maxGapMinutes: 180, maxDistanceKm: 200 })).toEqual([
[venice.id, verona.id],
]);
});
it('JRNPHOTOS-HELP-012: a photo without a position joins the group of its day nearest in time and never splits one', () => {
const v1 = photo('2026-05-14T07:00:00Z', VENICE);
const inside = photo('2026-05-14T07:20:00Z', null);
const v2 = photo('2026-05-14T07:40:00Z', VENICE);
const r1 = photo('2026-05-14T08:30:00Z', VERONA);
const nearVerona = photo('2026-05-14T08:20:00Z', null);
const longAfter = photo('2026-05-14T18:00:00Z', null);
expect(groups([v1, inside, v2, r1, nearVerona, longAfter])).toEqual([
[v1.id, inside.id, v2.id],
[nearVerona.id, r1.id, longAfter.id],
]);
});
it('JRNPHOTOS-HELP-013: a day with no geotagged photo is cut by time alone', () => {
const a = photo('2026-05-14T07:00:00Z', null);
const b = photo('2026-05-14T08:00:00Z', null);
const c = photo('2026-05-14T15:00:00Z', null);
expect(groups([a, b, c], 'UTC')).toEqual([[a.id, b.id], [c.id]]);
});
it('JRNPHOTOS-HELP-014: days come in the order they were lived', () => {
const second = photo('2026-05-15T07:00:00Z', VENICE);
const first = photo('2026-05-14T07:00:00Z', VENICE);
expect(groups([second, first])).toEqual([[first.id], [second.id]]);
});
});
describe('summarizeCluster', () => {
it('JRNPHOTOS-HELP-015: a group is dated, timed and placed by its photos; a clip is the cover only when nothing else is', () => {
const clip = photo('2026-05-14T07:00:00Z', VENICE, { mediaType: 'video' });
const picture = photo('2026-05-14T07:30:00Z', MURANO);
const blind = photo('2026-05-14T09:15:00Z', null);
const [cluster] = clusterCaptures(localCaptures([blind, picture, clip], null), THRESHOLDS);
const summary = summarizeCluster(cluster ?? []);
expect(summary).toEqual({
date: '2026-05-14',
startTime: '09:00',
endTime: '11:15',
zone: 'Europe/Rome',
lat: 45.44635,
lng: 12.3462,
photoIds: [clip.id, picture.id, blind.id],
coverPhotoId: picture.id,
});
const [onlyClip] = clusterCaptures(localCaptures([clip], null), THRESHOLDS);
expect(summarizeCluster(onlyClip ?? []).coverPhotoId).toBe(clip.id);
});
it('JRNPHOTOS-HELP-016: a group without a geotagged photo has no middle', () => {
const [cluster] = clusterCaptures(localCaptures([photo('2026-05-14T07:00:00Z', null)], 'Europe/Rome'), THRESHOLDS);
expect(summarizeCluster(cluster ?? [])).toMatchObject({
lat: null,
lng: null,
zone: 'Europe/Rome',
startTime: '09:00',
});
});
});
describe('centroid', () => {
it('JRNPHOTOS-HELP-017: the middle of two points either side of the antimeridian stays on the antimeridian', () => {
const middle = centroid([
{ lat: -16, lng: 179.9 },
{ lat: -17, lng: -179.9 },
]);
expect(middle?.lat).toBe(-16.5);
expect(Math.abs(middle?.lng ?? 0)).toBeCloseTo(180, 5);
expect(centroid([])).toBeNull();
});
});
describe('fallbackTitle', () => {
it('JRNPHOTOS-HELP-018: the country in the language, else the day written out', () => {
expect(fallbackTitle('it', '2026-05-14', 'de')).toEqual({ title: 'Italien', source: 'country' });
expect(fallbackTitle('IT', '2026-05-14', undefined)).toEqual({ title: 'Italy', source: 'country' });
expect(fallbackTitle(null, '2026-05-14', 'en-GB')).toEqual({ title: '14 May 2026', source: 'date' });
});
it("JRNPHOTOS-HELP-019: TREK's own codes for Brazilian Portuguese and Greek are read as those languages", () => {
expect(intlLanguage('br')).toBe('pt-BR');
expect(intlLanguage('gr')).toBe('el');
expect(intlLanguage('de')).toBe('de');
expect(intlLanguage(undefined)).toBeUndefined();
expect(fallbackTitle('IT', '2026-05-14', 'br')).toEqual({ title: 'Itália', source: 'country' });
});
});
@@ -0,0 +1,186 @@
/**
* JourneyEntriesFromPhotosMcp (#1920): draft entries from gallery photos over
* MCP, on the same service, refusals and journey access as REST. The suite
* takes its subject from a module over a snapshot test db; only the geocoder
* is replaced.
*/
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 type { McpContext } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonsModule } from '../../../../src/nest/addons/addons.module';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { JourneyDomainModule } from '../../../../src/nest/journey/journey-domain.module';
import { JourneyEntriesFromPhotosMcp } from '../../../../src/nest/journey/journey-entries-from-photos.mcp';
import { JourneyEntriesFromPhotosService } from '../../../../src/nest/journey/journey-entries-from-photos.service';
import { MapsService } from '../../../../src/nest/maps/maps.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../../helpers/factories/journeys';
import { countRows, findRows, insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import {
journeyEntriesFromPhotosCreateRequestSchema,
journeyEntriesFromPhotosCreateResponseSchema,
journeyEntriesFromPhotosPreviewRequestSchema,
journeyEntriesFromPhotosPreviewResponseSchema,
} from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
const reverseGeocode = vi.fn();
let t: TestModule;
let orm: TestOrm;
let mcp: JourneyEntriesFromPhotosMcp;
let service: JourneyEntriesFromPhotosService;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [JourneyDomainModule, AddonsModule, MikroOrmModule.forFeature([JourneyPhotos, JourneyEntryPhotos])],
providers: [
JourneyEntriesFromPhotosService,
JourneyEntriesFromPhotosMcp,
{ provide: MapsService, useValue: { reverseGeocode } },
],
});
mcp = t.get(JourneyEntriesFromPhotosMcp);
service = t.get(JourneyEntriesFromPhotosService);
orm = await createTestOrm(db);
});
beforeEach(() => {
resetTestDb(db);
orm.clear();
t.realtime.reset();
vi.restoreAllMocks();
reverseGeocode.mockReset().mockResolvedValue({ name: 'Venezia', address: null });
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
async function fixture() {
const { user: owner } = await makeUser(orm);
const { user: viewer } = await makeUser(orm);
const journey = await makeJourney(orm, owner.id, { title: 'Venice' });
await addJourneyContributor(orm, journey.id, viewer.id, 'viewer');
const photo = async (takenAt: string) => {
const photoId = await insertRow(orm, TrekPhotos, {
provider: 'local',
owner: owner.id,
file_path: 'journey/p.jpg',
taken_at: takenAt,
lat: 45.4341,
lng: 12.3388,
});
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 evening = await photo('2026-05-14T17:00:00Z');
return { owner, viewer, journey, morning, evening };
}
describe('JourneyEntriesFromPhotosMcp', () => {
it('JRNPHOTOS-MCP-001: the preview answers exactly what the service answers REST, and writes nothing', async () => {
const f = await fixture();
const viaTool = read(await mcp.previewEntriesFromPhotos({ journeyId: f.journey.id, lang: 'it' }, ctx(f.owner.id)));
const viaService = await service.preview(f.owner.id, f.journey.id, { lang: 'it' });
expect(viaTool).toEqual(viaService);
expect(journeyEntriesFromPhotosPreviewResponseSchema.parse(viaTool).clusters.map((c) => c.photoIds)).toEqual([
[f.morning],
[f.evening],
]);
expect(await countRows(orm, JourneyEntries)).toBe(0);
});
it('JRNPHOTOS-MCP-002: the create writes the drafts with their photos and tells everyone on the journey', async () => {
const f = await fixture();
const result = read(
await mcp.createEntriesFromPhotos(
{
journeyId: f.journey.id,
groups: [{ photoIds: [f.morning, f.evening], title: 'All day', locationName: 'Venezia' }],
},
ctx(f.owner.id),
),
);
expect(journeyEntriesFromPhotosCreateResponseSchema.parse(result)).toEqual({
entries: [
{ id: expect.any(Number), title: 'All day', entry_date: '2026-05-14', entry_time: '09:00', photoCount: 2 },
],
skippedPhotoIds: [],
});
expect(await findRows(orm, JourneyEntries, { journey: f.journey.id })).toEqual([
expect.objectContaining({ title: 'All day', is_draft: 1, location_name: 'Venezia' }),
]);
// MCP leaves no tab out: the assistant's own tab shows the change too.
expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(
f.viewer.id,
expect.objectContaining({ type: 'journey:entry:created', journeyId: f.journey.id }),
undefined,
);
});
it('JRNPHOTOS-MCP-003: refuses what REST refuses: a viewer previews and writes nothing', async () => {
const f = await fixture();
await expect(mcp.previewEntriesFromPhotos({ journeyId: f.journey.id }, ctx(f.viewer.id))).rejects.toThrow();
await expect(
mcp.createEntriesFromPhotos({ journeyId: f.journey.id, groups: [{ photoIds: [f.morning] }] }, ctx(f.viewer.id)),
).rejects.toThrow();
expect(await countRows(orm, JourneyEntries)).toBe(0);
});
it('JRNPHOTOS-MCP-004: both tools need the Journey addon; the preview reads and reaches out, the create writes', async () => {
const options = (name: string) => {
const entry = getEntry(JourneyEntriesFromPhotosMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
const ALL = ['previewEntriesFromPhotos', 'createEntriesFromPhotos'];
const gates = () => Promise.all(ALL.map((name) => options(name).when?.(ctx(1), mcp)));
expect(await gates()).toEqual([true, true]);
enabled.mockResolvedValue(false);
expect(await gates()).toEqual([false, false]);
expect(options('previewEntriesFromPhotos')).toMatchObject({
name: 'preview_journey_entries_from_photos',
access: { group: 'journey', mode: 'read' },
annotations: { readOnlyHint: true, openWorldHint: true },
});
expect(options('createEntriesFromPhotos')).toMatchObject({
name: 'create_journey_entries_from_photos',
access: { group: 'journey', mode: 'write' },
});
expect(options('createEntriesFromPhotos').annotations?.readOnlyHint).not.toBe(true);
});
it('JRNPHOTOS-MCP-005: the tool arguments are the REST bodies plus the journey id', () => {
const fieldsOf = (name: string) => {
const entry = getEntry(JourneyEntriesFromPhotosMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return Object.keys(entry.options.inputSchema ?? {}).sort();
};
expect(fieldsOf('previewEntriesFromPhotos')).toEqual(
['journeyId', ...Object.keys(journeyEntriesFromPhotosPreviewRequestSchema.shape)].sort(),
);
expect(fieldsOf('createEntriesFromPhotos')).toEqual(
['journeyId', ...Object.keys(journeyEntriesFromPhotosCreateRequestSchema.shape)].sort(),
);
});
});
@@ -0,0 +1,368 @@
/**
* JourneyEntriesFromPhotosService (#1920): draft entries made from the photos
* of a journey's gallery. The suite takes the service out of a module over a
* snapshot test db with the real journey domain, gallery and entry links;
* only the geocoder is replaced, so no test asks a network for a place name.
*
* What it pins: the preview groups the photos on no entry by local day, time
* and distance and names each group (place, else country, else day) without
* writing; the create writes one draft per group with its photos in one
* transaction, leaves out a photo that is on an entry by now or named twice,
* never touches an existing entry, announces the new entries after the commit
* and leaves nothing behind when it fails; only an editor of the journey may
* do either.
*/
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 { DomainError } from '../../../../src/nest/common/domain-error';
import { JourneyDomainModule } from '../../../../src/nest/journey/journey-domain.module';
import { JourneyDomainService } from '../../../../src/nest/journey/journey-domain.service';
import {
FROM_PHOTOS_MAX_GEOCODED,
JourneyEntriesFromPhotosService,
} from '../../../../src/nest/journey/journey-entries-from-photos.service';
import { MapsService } from '../../../../src/nest/maps/maps.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../../../helpers/factories/journeys';
import { countRows, findRow, findRows, insertRow } from '../../../helpers/factories/rows';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
const reverseGeocode = vi.fn<(...args: unknown[]) => Promise<{ name: string | null; address: string | null }>>();
let t: TestModule;
let orm: TestOrm;
let svc: JourneyEntriesFromPhotosService;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [JourneyDomainModule, MikroOrmModule.forFeature([JourneyPhotos, JourneyEntryPhotos])],
providers: [JourneyEntriesFromPhotosService, { provide: MapsService, useValue: { reverseGeocode } }],
});
svc = t.get(JourneyEntriesFromPhotosService);
orm = await createTestOrm(db);
});
beforeEach(() => {
resetTestDb(db);
orm.clear();
t.realtime.reset();
vi.restoreAllMocks();
reverseGeocode.mockReset().mockResolvedValue({ name: 'Venezia', address: 'Venezia, Veneto, Italia' });
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const VENICE = { lat: 45.4341, lng: 12.3388 };
const VERONA = { lat: 45.4384, lng: 10.9916 };
async function fixture() {
const { user: owner } = await makeUser(orm, { username: 'marta' });
const { user: editor } = await makeUser(orm, { username: 'jonas' });
const { user: viewer } = await makeUser(orm);
const { user: outsider } = 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');
return { owner, editor, viewer, outsider, journey };
}
/** A gallery photo of the journey; its journey photo id. */
async function galleryPhoto(
journeyId: number,
ownerId: number,
takenAt: string | null,
where: { lat: number; lng: number } | null = VENICE,
mediaType = 'image',
): Promise<number> {
const photoId = await insertRow(orm, TrekPhotos, {
provider: 'local',
owner: ownerId,
file_path: 'journey/p.jpg',
taken_at: takenAt,
lat: where?.lat ?? null,
lng: where?.lng ?? null,
media_type: mediaType,
});
return insertRow(orm, JourneyPhotos, { journey: journeyId, photo: photoId, sort_order: 0, created_at: Date.now() });
}
/** The status and message of the DomainError a call was refused with. */
async function refusal(promise: Promise<unknown>): Promise<{ status: number; error: unknown }> {
const err = await promise.then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(DomainError);
return { status: (err as DomainError).getStatus(), error: (err as DomainError).toBody().error };
}
const linksOf = async (entryId: number) =>
(await findRows(orm, JourneyEntryPhotos, { entry: entryId }))
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
.map((row) => row.journey_photo_id);
describe('JourneyEntriesFromPhotosService.preview', () => {
it('JRNPHOTOS-SVC-001: groups the photos on no entry by day, time and distance and names each, writing nothing', async () => {
const { owner, journey } = await fixture();
// Day one in Venice: two photos in the morning, one in the evening (a gap), one in Verona at noon (a distance).
const v1 = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
const v2 = await galleryPhoto(journey.id, owner.id, '2026-05-14T08:00:00Z', null);
const verona = await galleryPhoto(journey.id, owner.id, '2026-05-14T10:00:00Z', VERONA);
const evening = await galleryPhoto(journey.id, owner.id, '2026-05-14T17:30:00Z');
// Day two, Venice again: the same point is asked once.
const next = await galleryPhoto(journey.id, owner.id, '2026-05-15T07:00:00Z');
await galleryPhoto(journey.id, owner.id, null);
const entry = await makeJourneyEntry(orm, journey.id, owner.id);
const linked = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:10:00Z');
await insertRow(orm, JourneyEntryPhotos, { entry: entry.id, journeyPhoto: linked, sort_order: 0, created_at: 0 });
reverseGeocode.mockImplementation(async (lat) =>
String(lat).startsWith('45.43') && Number(lat) < 45.437
? { name: 'Venezia', address: null }
: { name: null, address: null },
);
const preview = await svc.preview(owner.id, journey.id, { lang: 'de' });
expect(preview.maxGapMinutes).toBe(180);
expect(preview.maxDistanceKm).toBe(20);
expect(preview.withoutCaptureTime).toBe(1);
expect(preview.clusters.map((c) => c.photoIds)).toEqual([[v1, v2], [verona], [evening], [next]]);
expect(preview.clusters[0]).toEqual({
date: '2026-05-14',
startTime: '09:00',
endTime: '10:00',
timezone: 'Europe/Rome',
lat: VENICE.lat,
lng: VENICE.lng,
countryCode: 'IT',
locationName: 'Venezia',
suggestedTitle: 'Venezia',
titleSource: 'place',
photoIds: [v1, v2],
photoCount: 2,
coverPhotoId: v1,
});
// No place name for Verona: the country, in the language asked for.
expect(preview.clusters[1]).toMatchObject({
suggestedTitle: 'Italien',
titleSource: 'country',
locationName: null,
});
expect(preview.clusters[3]).toMatchObject({ date: '2026-05-15', suggestedTitle: 'Venezia' });
expect(reverseGeocode).toHaveBeenCalledTimes(2);
expect(reverseGeocode).toHaveBeenCalledWith(String(VENICE.lat), String(VENICE.lng), 'de', {
lane: 'interactive',
timeoutMs: 8000,
locality: true,
});
expect(await countRows(orm, JourneyEntries, { journey: journey.id })).toBe(1);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('JRNPHOTOS-SVC-002: a geocoder that fails names the group by its day, and the thresholds are the ones asked for', async () => {
const { owner, journey } = await fixture();
const a = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z', null);
const b = await galleryPhoto(journey.id, owner.id, '2026-05-14T08:30:00Z', null);
reverseGeocode.mockRejectedValue(new Error('down'));
const preview = await svc.preview(owner.id, journey.id, {
timezone: 'America/New_York',
maxGapMinutes: 60,
maxDistanceKm: 1,
lang: 'en-GB',
});
expect(preview).toMatchObject({ maxGapMinutes: 60, maxDistanceKm: 1, withoutCaptureTime: 0 });
expect(preview.clusters).toEqual([
expect.objectContaining({
photoIds: [a],
date: '2026-05-14',
startTime: '03:00',
timezone: 'America/New_York',
lat: null,
countryCode: null,
suggestedTitle: '14 May 2026',
titleSource: 'date',
}),
expect.objectContaining({ photoIds: [b], startTime: '04:30' }),
]);
expect(reverseGeocode).not.toHaveBeenCalled();
const located = await galleryPhoto(journey.id, owner.id, '2026-05-16T07:00:00Z');
const again = await svc.preview(owner.id, journey.id, {});
expect(again.clusters.find((c) => c.photoIds.includes(located))).toMatchObject({
titleSource: 'country',
suggestedTitle: 'Italy',
});
});
it('JRNPHOTOS-SVC-003: asks the geocoder about a bounded number of points and names the rest by country', async () => {
const { owner, journey } = await fixture();
// One group per day, each a few kilometres further east.
for (let day = 0; day < FROM_PHOTOS_MAX_GEOCODED + 2; day++) {
const date = new Date(Date.UTC(2026, 4, 1 + day, 7)).toISOString();
await galleryPhoto(journey.id, owner.id, date, { lat: 45.0, lng: 9 + day * 0.05 });
}
const preview = await svc.preview(owner.id, journey.id, {});
expect(reverseGeocode).toHaveBeenCalledTimes(FROM_PHOTOS_MAX_GEOCODED);
expect(preview.clusters.filter((c) => c.titleSource === 'place')).toHaveLength(FROM_PHOTOS_MAX_GEOCODED);
expect(preview.clusters.slice(-2).map((c) => c.titleSource)).toEqual(['country', 'country']);
});
it('JRNPHOTOS-SVC-004: only an editor may ask; a viewer is refused and a stranger does not learn the journey exists', async () => {
const { editor, viewer, outsider, journey } = await fixture();
await expect(svc.preview(editor.id, journey.id, {})).resolves.toMatchObject({ clusters: [] });
expect(await refusal(svc.preview(viewer.id, journey.id, {}))).toEqual({ status: 403, error: 'Not allowed' });
expect(await refusal(svc.preview(outsider.id, journey.id, {}))).toEqual({
status: 404,
error: 'Journey not found',
});
expect(await refusal(svc.preview(outsider.id, 999_999, {}))).toEqual({ status: 404, error: 'Journey not found' });
expect(reverseGeocode).not.toHaveBeenCalled();
});
});
describe('JourneyEntriesFromPhotosService.create', () => {
it('JRNPHOTOS-SVC-005: writes one draft per group with its photos, dated and placed by them, announced after the commit', async () => {
const { owner, editor, journey } = await fixture();
const a = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:30:00Z');
const b = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z', null);
const c = await galleryPhoto(journey.id, owner.id, '2026-05-15T09:00:00Z', VERONA);
const result = await svc.create(
editor.id,
journey.id,
{
groups: [{ photoIds: [a, b], title: 'Morning on San Marco', locationName: 'Venezia' }, { photoIds: [c] }],
lang: 'de',
},
'11',
);
expect(result).toEqual({
entries: [
{
id: expect.any(Number),
title: 'Morning on San Marco',
entry_date: '2026-05-14',
entry_time: '09:00',
photoCount: 2,
},
{ id: expect.any(Number), title: 'Italien', entry_date: '2026-05-15', entry_time: '11:00', photoCount: 1 },
],
skippedPhotoIds: [],
});
const [first, second] = result.entries;
expect(await findRow(orm, JourneyEntries, { id: first?.id })).toMatchObject({
author_id: editor.id,
type: 'entry',
is_draft: 1,
location_name: 'Venezia',
location_lat: VENICE.lat,
location_lng: VENICE.lng,
country_code: 'IT',
});
expect(await findRow(orm, JourneyEntries, { id: second?.id })).toMatchObject({ location_name: null, is_draft: 1 });
// In the order they were taken.
expect(await linksOf(first?.id ?? 0)).toEqual([b, a]);
expect(await linksOf(second?.id ?? 0)).toEqual([c]);
const created = t.realtime.broadcastToUserMock.mock.calls.filter(
([, event]) => event.type === 'journey:entry:created',
);
// Two entries, each to the owner and the two contributors, leaving out the asking tab.
expect(created).toHaveLength(6);
expect(created[0]).toEqual([expect.any(Number), expect.objectContaining({ journeyId: journey.id }), '11']);
});
it('JRNPHOTOS-SVC-006: a photo put on an entry meanwhile, named twice or from elsewhere is left out; existing entries stay as they were', async () => {
const { owner, journey } = await fixture();
const other = await makeJourney(orm, owner.id);
const existing = await makeJourneyEntry(orm, journey.id, owner.id, { title: 'Arrival', updated_at: 5 });
const meanwhile = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
const free = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:10:00Z');
const foreign = await galleryPhoto(other.id, owner.id, '2026-05-14T07:20:00Z');
const untimed = await galleryPhoto(journey.id, owner.id, null);
const onlyLinked = await galleryPhoto(journey.id, owner.id, '2026-05-16T07:00:00Z');
const preview = await svc.preview(owner.id, journey.id, {});
expect(preview.clusters.flatMap((cluster) => cluster.photoIds)).toEqual([meanwhile, free, onlyLinked]);
await insertRow(orm, JourneyEntryPhotos, {
entry: existing.id,
journeyPhoto: meanwhile,
sort_order: 0,
created_at: 0,
});
await insertRow(orm, JourneyEntryPhotos, {
entry: existing.id,
journeyPhoto: onlyLinked,
sort_order: 1,
created_at: 0,
});
const result = await svc.create(owner.id, journey.id, {
groups: [
{ photoIds: [meanwhile, free, foreign, untimed], title: 'Venice' },
{ photoIds: [free], title: 'Twice' },
{ photoIds: [onlyLinked], title: 'Nothing left' },
],
});
expect(result.entries).toEqual([expect.objectContaining({ title: 'Venice', photoCount: 1 })]);
expect(result.skippedPhotoIds).toEqual([meanwhile, foreign, untimed, free, onlyLinked]);
expect(await linksOf(result.entries[0]?.id ?? 0)).toEqual([free]);
expect(await linksOf(existing.id)).toEqual([meanwhile, onlyLinked]);
expect(await findRow(orm, JourneyEntries, { id: existing.id })).toMatchObject({ title: 'Arrival', updated_at: 5 });
expect(await countRows(orm, JourneyEntries, { journey: journey.id })).toBe(2);
});
it('JRNPHOTOS-SVC-007: a failure halfway leaves no entry and no link behind, and announces nothing', async () => {
const { owner, journey } = await fixture();
const a = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
const b = await galleryPhoto(journey.id, owner.id, '2026-05-15T07:00:00Z');
const domain = t.get(JourneyDomainService);
const real = domain.createEntry.bind(domain);
let calls = 0;
vi.spyOn(domain, 'createEntry').mockImplementation(async (...args) => {
calls++;
if (calls === 2) throw new Error('disk full');
return await real(...args);
});
await expect(svc.create(owner.id, journey.id, { groups: [{ photoIds: [a] }, { photoIds: [b] }] })).rejects.toThrow(
'disk full',
);
expect(await countRows(orm, JourneyEntries, { journey: journey.id })).toBe(0);
expect(await countRows(orm, JourneyEntryPhotos)).toBe(0);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('JRNPHOTOS-SVC-008: only an editor may create; a viewer and a stranger write nothing', async () => {
const { viewer, outsider, journey, owner } = await fixture();
const a = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
const body = { groups: [{ photoIds: [a] }] };
expect(await refusal(svc.create(viewer.id, journey.id, body))).toEqual({ status: 403, error: 'Not allowed' });
expect(await refusal(svc.create(outsider.id, journey.id, body))).toEqual({
status: 404,
error: 'Journey not found',
});
expect(await countRows(orm, JourneyEntries)).toBe(0);
});
it('JRNPHOTOS-SVC-009: a create whose photos are all gone writes nothing and says so', async () => {
const { owner, journey } = await fixture();
const result = await svc.create(owner.id, journey.id, { groups: [{ photoIds: [424242] }] });
expect(result).toEqual({ entries: [], skippedPhotoIds: [424242] });
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
});