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:
@@ -43,6 +43,18 @@ export interface JourneyPublicAssetValidationRow {
|
||||
journey_owner_id: number;
|
||||
}
|
||||
|
||||
/** A gallery photo on no entry, as {@link JourneyPhotosRepository.listOffEntries} reads it. */
|
||||
export interface JourneyPhotoOffEntryRow {
|
||||
/** The gallery row (journey photo id). */
|
||||
id: number;
|
||||
photo_id: number;
|
||||
/** ISO capture instant; null when the photo does not know it (an empty value reads as null). */
|
||||
taken_at: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
media_type: string;
|
||||
}
|
||||
|
||||
/** `GALLERY_SELECT`'s exact column list (`journey-domain.service.ts`'s module const), aliased `gp`/`tp` — shared by every gallery-shaped read below. */
|
||||
const GALLERY_COLUMNS = [
|
||||
'gp.id',
|
||||
@@ -420,6 +432,41 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
|
||||
return row as GalleryPhoto | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The gallery photos of a journey that sit on no entry (of any kind, a
|
||||
* suggestion included), with when and where they were taken: what the
|
||||
* journal can still make entries of (#1920). A photo without a capture
|
||||
* time comes back too, with `taken_at` null, so the caller can count it.
|
||||
* In gallery-row order, which the caller re-sorts by capture time.
|
||||
*/
|
||||
async listOffEntries(journeyId: number): Promise<JourneyPhotoOffEntryRow[]> {
|
||||
const rows = await this.kysely<GalleryKyselyDB>()
|
||||
.selectFrom('journey_photos as gp')
|
||||
.innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
|
||||
.select(['gp.id', 'gp.photo_id', 'tp.taken_at', 'tp.lat', 'tp.lng', 'tp.media_type'])
|
||||
.where('gp.journey_id', '=', journeyId)
|
||||
.where((eb) =>
|
||||
eb.not(
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('journey_entry_photos as jep')
|
||||
.select('jep.entry_id')
|
||||
.whereRef('jep.journey_photo_id', '=', 'gp.id'),
|
||||
),
|
||||
),
|
||||
)
|
||||
.orderBy('gp.id', 'asc')
|
||||
.execute();
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
photo_id: row.photo_id,
|
||||
taken_at: row.taken_at || null,
|
||||
lat: row.lat ?? null,
|
||||
lng: row.lng ?? null,
|
||||
media_type: row.media_type,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* JG19 — `getJourneyFull`'s gallery read, folding in `GALLERY_CHRONOLOGICAL_ORDER`
|
||||
* (R1). Task 1's report left this raw for this task to finish (its own
|
||||
|
||||
@@ -59,6 +59,7 @@ import { AirtrailModule } from './integrations/airtrail.module';
|
||||
import { DawarichModule } from './integrations/dawarich.module';
|
||||
import { JourneyRecordingsModule } from './journey-recordings/journey-recordings.module';
|
||||
import { JourneyAccessModule } from './journey/journey-access.module';
|
||||
import { JourneyEntriesFromPhotosModule } from './journey/journey-entries-from-photos.module';
|
||||
import { JourneyModule } from './journey/journey.module';
|
||||
import { TripJournalLinkModule } from './journey/trip-journal-link.module';
|
||||
import { LlmParseModule } from './llm-parse/llm-parse.module';
|
||||
@@ -206,6 +207,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
DawarichModule,
|
||||
JourneyModule,
|
||||
JourneyRecordingsModule,
|
||||
JourneyEntriesFromPhotosModule,
|
||||
TripJournalLinkModule,
|
||||
CollectionsModule,
|
||||
PlacesLibraryModule,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import { JourneyEntriesFromPhotosCreateDto, JourneyEntriesFromPhotosPreviewDto } from './journey.dto';
|
||||
import { Body, Controller, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
journeyEntriesFromPhotosCreateResponseSchema,
|
||||
journeyEntriesFromPhotosPreviewResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920), at
|
||||
* `/api/journeys/:id/entries/from-photos`. Both need the right to edit the
|
||||
* journey (404 for one the caller cannot see, 403 for a viewer). The preview
|
||||
* is a POST because it takes options and asks the geocoder; it writes
|
||||
* nothing. The create answers 200 with what it wrote and what it left out.
|
||||
*/
|
||||
@Controller('api/journeys/:id/entries/from-photos')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
|
||||
export class JourneyEntriesFromPhotosController {
|
||||
constructor(private readonly fromPhotos: JourneyEntriesFromPhotosService) {}
|
||||
|
||||
@Post('preview')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(journeyEntriesFromPhotosPreviewResponseSchema)
|
||||
async preview(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Journey not found')) id: number,
|
||||
@Body() body: JourneyEntriesFromPhotosPreviewDto,
|
||||
) {
|
||||
return await this.fromPhotos.preview(user.id, id, body);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@ResponseContract(journeyEntriesFromPhotosCreateResponseSchema)
|
||||
async create(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Journey not found')) id: number,
|
||||
@Body() body: JourneyEntriesFromPhotosCreateDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return await this.fromPhotos.create(user.id, id, body, socketId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import { haversineKm } from '../common/geo';
|
||||
import { localParts, resolveTimeZone } from '../common/timezoneService';
|
||||
|
||||
/**
|
||||
* The pure half of making journal entries from gallery photos (#1920): when
|
||||
* each photo was taken on the local clock, and how a day's photos fall into
|
||||
* groups. No database, no network; the service and its tests share it.
|
||||
*/
|
||||
|
||||
/** A gallery photo on no entry that knows when it was taken. */
|
||||
export interface FromPhotosPhoto {
|
||||
/** The gallery row (journey photo id). */
|
||||
id: number;
|
||||
/** The capture instant as stored: ISO 8601, with `Z`, an offset or neither. */
|
||||
takenAt: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
mediaType: string;
|
||||
}
|
||||
|
||||
/** A photo placed on the local clock of the zone its day is read in. */
|
||||
export interface LocalCapture extends FromPhotosPhoto {
|
||||
/** Milliseconds since the epoch. */
|
||||
instant: number;
|
||||
/** `YYYY-MM-DD` and `HH:MM` on that clock. */
|
||||
date: string;
|
||||
time: string;
|
||||
/** An IANA zone name, or `UTC+02:00` for an offset the capture time carried. */
|
||||
zone: string;
|
||||
/** Whether lat/lng are a usable position. */
|
||||
located: boolean;
|
||||
}
|
||||
|
||||
interface ClusterThresholds {
|
||||
maxGapMinutes: number;
|
||||
maxDistanceKm: number;
|
||||
}
|
||||
|
||||
/** What one group of photos becomes, before it has a title. */
|
||||
export interface ClusterSummary {
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
zone: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
photoIds: number[];
|
||||
coverPhotoId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far in time the nearest geotagged photo may be for a photo without a
|
||||
* position to borrow its zone. Further away, it may well have been taken
|
||||
* somewhere else, and the caller's zone is as good a guess.
|
||||
*/
|
||||
const BORROWED_ZONE_WINDOW_MS = 72 * 60 * 60 * 1000;
|
||||
|
||||
/** An offset written after a clock time: `+02:00`, `-0530`. `Z` is not one (see {@link carriedOffsetMinutes}). */
|
||||
const CARRIED_OFFSET = /T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?([+-])(\d{2}):?(\d{2})$/;
|
||||
|
||||
/**
|
||||
* The offset a stored capture time carries, in minutes east of UTC, or null.
|
||||
*
|
||||
* `Z` counts as no offset on purpose: TREK's own EXIF reader and the photo
|
||||
* libraries hand over the instant converted to UTC, so a `Z` says nothing
|
||||
* about the clock the photo was taken on. An explicit `+02:00` does.
|
||||
*/
|
||||
export function carriedOffsetMinutes(takenAt: string): number | null {
|
||||
const m = CARRIED_OFFSET.exec(takenAt.trim());
|
||||
if (!m) return null;
|
||||
const hours = Number(m[2]);
|
||||
const minutes = Number(m[3]);
|
||||
if (hours > 14 || minutes > 59) return null;
|
||||
return (m[1] === '-' ? -1 : 1) * (hours * 60 + minutes);
|
||||
}
|
||||
|
||||
/** Whether a pair is a position: finite, on the globe, and not the 0,0 a receiver without a fix writes. */
|
||||
export function isLocated(lat: number | null, lng: number | null): boolean {
|
||||
if (lat === null || lng === null || !Number.isFinite(lat) || !Number.isFinite(lng)) return false;
|
||||
if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return false;
|
||||
return !(lat === 0 && lng === 0);
|
||||
}
|
||||
|
||||
function offsetLabel(minutes: number): string {
|
||||
const sign = minutes < 0 ? '-' : '+';
|
||||
const abs = Math.abs(minutes);
|
||||
const hh = String(Math.floor(abs / 60)).padStart(2, '0');
|
||||
const mm = String(abs % 60).padStart(2, '0');
|
||||
return `UTC${sign}${hh}:${mm}`;
|
||||
}
|
||||
|
||||
/** The local date and time of an instant at a fixed offset. */
|
||||
function atOffset(instant: number, minutes: number): { date: string; time: string } {
|
||||
const shifted = new Date(instant + minutes * 60_000).toISOString();
|
||||
return { date: shifted.slice(0, 10), time: shifted.slice(11, 16) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every photo on the clock its day is read on. In order of preference: the
|
||||
* offset its capture time carries; the zone of the place it was taken; the
|
||||
* zone of the geotagged photo of the same set nearest in time (within three
|
||||
* days), since TREK keeps no zone on a journey or a trip; `fallbackZone` (the
|
||||
* caller's device zone, already checked to be a known one); UTC. A photo
|
||||
* whose capture time does not parse is left out.
|
||||
*/
|
||||
export function localCaptures(photos: readonly FromPhotosPhoto[], fallbackZone: string | null): LocalCapture[] {
|
||||
const parsed = photos
|
||||
.map((photo) => ({ photo, instant: Date.parse(photo.takenAt) }))
|
||||
.filter((p) => Number.isFinite(p.instant));
|
||||
// The zones the photos' own positions name, for those without one to borrow.
|
||||
const geoZones = parsed
|
||||
.map((p) => ({
|
||||
instant: p.instant,
|
||||
zone: isLocated(p.photo.lat, p.photo.lng) ? resolveTimeZone(p.photo.lat, p.photo.lng) : null,
|
||||
}))
|
||||
.filter((z): z is { instant: number; zone: string } => z.zone !== null);
|
||||
|
||||
const borrowed = (instant: number): string | null => {
|
||||
let best: { distance: number; zone: string } | null = null;
|
||||
for (const candidate of geoZones) {
|
||||
const distance = Math.abs(candidate.instant - instant);
|
||||
if (distance <= BORROWED_ZONE_WINDOW_MS && (!best || distance < best.distance)) {
|
||||
best = { distance, zone: candidate.zone };
|
||||
}
|
||||
}
|
||||
return best?.zone ?? null;
|
||||
};
|
||||
|
||||
return parsed.map(({ photo, instant }) => {
|
||||
const located = isLocated(photo.lat, photo.lng);
|
||||
const offset = carriedOffsetMinutes(photo.takenAt);
|
||||
if (offset !== null) return { ...photo, instant, ...atOffset(instant, offset), zone: offsetLabel(offset), located };
|
||||
const zone = (located ? resolveTimeZone(photo.lat, photo.lng) : null) ?? borrowed(instant) ?? fallbackZone ?? 'UTC';
|
||||
const parts = localParts(new Date(instant).toISOString(), zone);
|
||||
// localParts answers nulls only for a zone the runtime does not know; UTC then.
|
||||
if (!parts.date || !parts.time) return { ...photo, instant, ...atOffset(instant, 0), zone: 'UTC', located };
|
||||
return { ...photo, instant, date: parts.date, time: parts.time, zone, located };
|
||||
});
|
||||
}
|
||||
|
||||
const byInstant = (a: LocalCapture, b: LocalCapture) => a.instant - b.instant || a.id - b.id;
|
||||
|
||||
/**
|
||||
* The photos of one local day in groups. The geotagged ones are walked in
|
||||
* the order they were taken, and a new group starts where the time to the
|
||||
* previous one exceeds the gap or the distance to the previous one exceeds
|
||||
* the distance. A photo without a position then joins the group of its day
|
||||
* nearest to it in time (one it falls inside of first, the earlier one on a
|
||||
* tie). A day with no geotagged photo at all is cut by time alone.
|
||||
*/
|
||||
function clusterDay(day: LocalCapture[], thresholds: ClusterThresholds): LocalCapture[][] {
|
||||
const gapMs = thresholds.maxGapMinutes * 60_000;
|
||||
const located = day.filter((c) => c.located);
|
||||
const unlocated = day.filter((c) => !c.located);
|
||||
const clusters: LocalCapture[][] = [];
|
||||
const walk = (photos: LocalCapture[], byDistance: boolean) => {
|
||||
let current: LocalCapture[] = [];
|
||||
for (const photo of photos) {
|
||||
const last = current[current.length - 1];
|
||||
const tooLate = last !== undefined && photo.instant - last.instant > gapMs;
|
||||
const tooFar =
|
||||
byDistance &&
|
||||
last !== undefined &&
|
||||
haversineKm(last.lat as number, last.lng as number, photo.lat as number, photo.lng as number) >
|
||||
thresholds.maxDistanceKm;
|
||||
if (last !== undefined && (tooLate || tooFar)) {
|
||||
clusters.push(current);
|
||||
current = [];
|
||||
}
|
||||
current.push(photo);
|
||||
}
|
||||
if (current.length) clusters.push(current);
|
||||
};
|
||||
|
||||
if (!located.length) {
|
||||
walk(unlocated, false);
|
||||
return clusters;
|
||||
}
|
||||
walk(located, true);
|
||||
for (const photo of unlocated) {
|
||||
let best: { distance: number; cluster: LocalCapture[] } | null = null;
|
||||
for (const cluster of clusters) {
|
||||
const first = (cluster[0] as LocalCapture).instant;
|
||||
const last = (cluster[cluster.length - 1] as LocalCapture).instant;
|
||||
const distance = photo.instant < first ? first - photo.instant : Math.max(0, photo.instant - last);
|
||||
if (!best || distance < best.distance) best = { distance, cluster };
|
||||
}
|
||||
(best as { cluster: LocalCapture[] }).cluster.push(photo);
|
||||
}
|
||||
for (const cluster of clusters) cluster.sort(byInstant);
|
||||
return clusters;
|
||||
}
|
||||
|
||||
/** The photos in groups: by local day first, then by time and distance inside a day, in the order they were lived. */
|
||||
export function clusterCaptures(captures: readonly LocalCapture[], thresholds: ClusterThresholds): LocalCapture[][] {
|
||||
const days = new Map<string, LocalCapture[]>();
|
||||
for (const capture of [...captures].sort(byInstant)) {
|
||||
const day = days.get(capture.date);
|
||||
if (day) day.push(capture);
|
||||
else days.set(capture.date, [capture]);
|
||||
}
|
||||
return [...days.values()]
|
||||
.flatMap((day) => clusterDay(day, thresholds))
|
||||
.sort((a, b) => byInstant(a[0] as LocalCapture, b[0] as LocalCapture));
|
||||
}
|
||||
|
||||
const round6 = (value: number) => Math.round(value * 1e6) / 1e6;
|
||||
|
||||
/**
|
||||
* The middle of the geotagged photos, or null. The longitude is a circular
|
||||
* mean, so a group either side of the antimeridian is not put on the far
|
||||
* side of the globe.
|
||||
*/
|
||||
export function centroid(points: readonly { lat: number; lng: number }[]): { lat: number; lng: number } | null {
|
||||
if (!points.length) return null;
|
||||
const toRad = Math.PI / 180;
|
||||
let lat = 0;
|
||||
let sin = 0;
|
||||
let cos = 0;
|
||||
for (const p of points) {
|
||||
lat += p.lat;
|
||||
sin += Math.sin(p.lng * toRad);
|
||||
cos += Math.cos(p.lng * toRad);
|
||||
}
|
||||
return { lat: round6(lat / points.length), lng: round6(Math.atan2(sin, cos) / toRad) };
|
||||
}
|
||||
|
||||
/**
|
||||
* One group's day, times, middle and cover. The group's day and zone are its
|
||||
* first photo's; its photos are in the order they were taken. The cover is
|
||||
* its first picture, a clip only when it holds nothing else.
|
||||
*/
|
||||
export function summarizeCluster(cluster: readonly LocalCapture[]): ClusterSummary {
|
||||
const sorted = [...cluster].sort(byInstant);
|
||||
const first = sorted[0] as LocalCapture;
|
||||
const last = sorted[sorted.length - 1] as LocalCapture;
|
||||
const middle = centroid(sorted.filter((c) => c.located) as { lat: number; lng: number }[]);
|
||||
const cover = sorted.find((c) => c.mediaType !== 'video') ?? first;
|
||||
return {
|
||||
date: first.date,
|
||||
startTime: first.time,
|
||||
endTime: last.date === first.date ? last.time : first.time,
|
||||
zone: first.zone,
|
||||
lat: middle?.lat ?? null,
|
||||
lng: middle?.lng ?? null,
|
||||
photoIds: sorted.map((c) => c.id),
|
||||
coverPhotoId: cover.id,
|
||||
};
|
||||
}
|
||||
|
||||
/** Intl.DisplayNames for the language, English when the runtime does not know it, null without ICU data. */
|
||||
function regionNames(lang: string | undefined): Intl.DisplayNames | null {
|
||||
for (const locale of [lang, 'en']) {
|
||||
if (!locale) continue;
|
||||
try {
|
||||
return new Intl.DisplayNames([locale], { type: 'region', fallback: 'none' });
|
||||
} catch {
|
||||
// An unknown tag: the next one.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A date written out in the language ('14 May 2026'), the ISO day when the runtime cannot. */
|
||||
function spelledDate(date: string, lang: string | undefined): string {
|
||||
for (const locale of [lang, 'en']) {
|
||||
if (!locale) continue;
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
}).format(new Date(`${date}T00:00:00Z`));
|
||||
} catch {
|
||||
// An unknown tag: the next one.
|
||||
}
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* The title a group gets when no place name was found for it: the country it
|
||||
* lies in, named in the language, else its day written out.
|
||||
*/
|
||||
export function fallbackTitle(
|
||||
countryCode: string | null,
|
||||
date: string,
|
||||
lang: string | undefined,
|
||||
): { title: string; source: 'country' | 'date' } {
|
||||
const tag = intlLanguage(lang);
|
||||
if (countryCode) {
|
||||
const name = regionNames(tag)?.of(countryCode.toUpperCase());
|
||||
if (name) return { title: name, source: 'country' };
|
||||
}
|
||||
return { title: spelledDate(date, tag), source: 'date' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The two TREK language codes that are not the BCP-47 tag of their language:
|
||||
* `br` is Brazilian Portuguese (bare `br` is Breton) and `gr` is Greek. An MCP
|
||||
* client may send either; the app sends the BCP-47 locale.
|
||||
*/
|
||||
const TREK_LANGUAGE_TAGS: Readonly<Record<string, string>> = { br: 'pt-BR', gr: 'el' };
|
||||
|
||||
/** The BCP-47 tag Intl reads for a language a caller named. */
|
||||
export function intlLanguage(lang: string | undefined): string | undefined {
|
||||
if (!lang) return undefined;
|
||||
return TREK_LANGUAGE_TAGS[lang] ?? lang;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import {
|
||||
McpController,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
Tool,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import {
|
||||
idSchema,
|
||||
journeyEntriesFromPhotosCreateRequestSchema,
|
||||
journeyEntriesFromPhotosPreviewRequestSchema,
|
||||
type JourneyEntriesFromPhotosCreateRequest,
|
||||
type JourneyEntriesFromPhotosPreviewRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920) over MCP:
|
||||
* the same service, the same edit right on the journey and the same events as
|
||||
* POST `/api/journeys/:id/entries/from-photos/preview` and
|
||||
* POST `/api/journeys/:id/entries/from-photos`.
|
||||
*/
|
||||
@McpController()
|
||||
export class JourneyEntriesFromPhotosMcp {
|
||||
constructor(
|
||||
private readonly fromPhotos: JourneyEntriesFromPhotosService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'preview_journey_entries_from_photos',
|
||||
description:
|
||||
"Group the photos of a journey's gallery that are on no entry yet and know when they were taken into proposed journal entries, without writing anything. Photos are grouped by local day (read in the offset the capture time carries, else the zone of the place it was taken, else the zone of the journey's geotagged photo nearest in time, else timezone, else UTC), then split inside a day where two photos are more than maxGapMinutes (default 180) or two geotagged ones more than maxDistanceKm (default 20) apart; a photo without a position joins the group of its day nearest in time. Each group has its date, start and end time, the middle of its geotagged photos with the country, a suggested title (a place name in lang, else the country, else the day), the journey photo ids and a cover photo. withoutCaptureTime counts the photos that belong to no group. Needs edit access to the journey.",
|
||||
inputSchema: { journeyId: idSchema, ...journeyEntriesFromPhotosPreviewRequestSchema.shape },
|
||||
// Asks the geocoder for place names; nothing of the journey changes.
|
||||
annotations: { ...TOOL_ANNOTATIONS_READONLY, openWorldHint: true },
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
async previewEntriesFromPhotos(
|
||||
{ journeyId, ...request }: { journeyId: number } & JourneyEntriesFromPhotosPreviewRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.fromPhotos.preview(ctx.userId, journeyId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'create_journey_entries_from_photos',
|
||||
description:
|
||||
"Write draft journal entries from groups of gallery photos, after the traveller chose them in preview_journey_entries_from_photos: one draft per group, dated and timed by its first photo, placed at the middle of its geotagged photos, with its photos on it. Pass each group as photoIds (journey photo ids), with title (the suggested title or the traveller's own; the country or day when left out) and locationName (the place name the preview found). Send the same timezone as the preview. All entries are written in one change; a photo that was put on an entry meanwhile, or is named twice, is left out and listed in skippedPhotoIds, and a group left without photos writes no entry. Existing entries are never changed, and drafts never appear on shared pages.",
|
||||
inputSchema: { journeyId: idSchema, ...journeyEntriesFromPhotosCreateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'write' },
|
||||
})
|
||||
async createEntriesFromPhotos(
|
||||
{ journeyId, ...request }: { journeyId: number } & JourneyEntriesFromPhotosCreateRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.fromPhotos.create(ctx.userId, journeyId, request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity';
|
||||
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyEntriesFromPhotosController } from './journey-entries-from-photos.controller';
|
||||
import { JourneyEntriesFromPhotosMcp } from './journey-entries-from-photos.mcp';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920): its
|
||||
* routes, its MCP tools and the service behind both.
|
||||
*
|
||||
* A module of its own because it names its groups through the geocoder
|
||||
* (MapsModule, a leaf), which JourneyDomainModule stays free of on purpose.
|
||||
* The entries go through JourneyDomainService; the gallery and the entry
|
||||
* links are read and written through their repositories here, inside the
|
||||
* one transaction the service opens.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
JourneyDomainModule,
|
||||
MapsModule,
|
||||
AddonsModule,
|
||||
MikroOrmModule.forFeature([JourneyPhotos, JourneyEntryPhotos]),
|
||||
],
|
||||
controllers: [JourneyEntriesFromPhotosController],
|
||||
providers: [JourneyEntriesFromPhotosService, JourneyEntriesFromPhotosMcp],
|
||||
})
|
||||
export class JourneyEntriesFromPhotosModule {}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity';
|
||||
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
|
||||
import type { JourneyEntryPhotosRepository } from '../../db/repositories/JourneyEntryPhotos.repository';
|
||||
import type { JourneyPhotoOffEntryRow, JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
|
||||
import { getCountryFromCoords } from '../../utils/country-borders';
|
||||
import { forbidden, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import {
|
||||
clusterCaptures,
|
||||
fallbackTitle,
|
||||
localCaptures,
|
||||
summarizeCluster,
|
||||
type ClusterSummary,
|
||||
type FromPhotosPhoto,
|
||||
type LocalCapture,
|
||||
} from './journey-entries-from-photos.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
JOURNEY_FROM_PHOTOS_DEFAULT_DISTANCE_KM,
|
||||
JOURNEY_FROM_PHOTOS_DEFAULT_GAP_MINUTES,
|
||||
type JourneyEntriesFromPhotosCluster,
|
||||
type JourneyEntriesFromPhotosCreateRequest,
|
||||
type JourneyEntriesFromPhotosCreateResponse,
|
||||
type JourneyEntriesFromPhotosPreviewRequest,
|
||||
type JourneyEntriesFromPhotosPreviewResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** The most groups one preview asks the geocoder to name; the rest are named by country or day. */
|
||||
export const FROM_PHOTOS_MAX_GEOCODED = 25;
|
||||
/** How long one preview spends naming places before it names the rest by country or day. */
|
||||
const FROM_PHOTOS_GEOCODE_BUDGET_MS = 20_000;
|
||||
/** The deadline of one place lookup, after the geocoder's own rate-limit wait. */
|
||||
const GEOCODE_TIMEOUT_MS = 8_000;
|
||||
|
||||
type CreatedEntry = NonNullable<Awaited<ReturnType<JourneyDomainService['createEntry']>>>;
|
||||
|
||||
/** The country a point falls in, from the bundled borders; null without a point or without the asset. */
|
||||
function countryOf(lat: number | null, lng: number | null): string | null {
|
||||
if (lat === null || lng === null) return null;
|
||||
try {
|
||||
return getCountryFromCoords(lat, lng);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The photos of the gallery on no entry, as the clustering reads them; the ones without a capture time apart. */
|
||||
function capturedOf(rows: readonly JourneyPhotoOffEntryRow[]): { captured: FromPhotosPhoto[]; withoutTime: number } {
|
||||
const captured: FromPhotosPhoto[] = [];
|
||||
let withoutTime = 0;
|
||||
for (const row of rows) {
|
||||
if (!row.taken_at) {
|
||||
withoutTime++;
|
||||
continue;
|
||||
}
|
||||
captured.push({ id: row.id, takenAt: row.taken_at, lat: row.lat, lng: row.lng, mediaType: row.media_type });
|
||||
}
|
||||
return { captured, withoutTime };
|
||||
}
|
||||
|
||||
/**
|
||||
* Journal entries made from the photos of a journey's gallery (#1920).
|
||||
*
|
||||
* The preview reads the gallery photos on no entry that know when they were
|
||||
* taken, puts each on the clock of its local day (the helpers say which zone
|
||||
* that is), groups them by day and, inside a day, by time and distance, and
|
||||
* names every group: a place name from the geocoder (the same client, cache
|
||||
* and rate limit as everywhere else, capped per preview), else the country,
|
||||
* else the day. It writes nothing.
|
||||
*
|
||||
* The create takes the groups the traveller kept, each a list of gallery
|
||||
* photo ids with an optional title, and writes one draft entry per group with
|
||||
* its photos linked, all in one transaction. The photos are read again inside
|
||||
* it, so one put on an entry since the preview (or named twice) is left out
|
||||
* and reported instead of linked twice, and a group left with none writes no
|
||||
* entry. Entries that existed before are never touched. The new entries are
|
||||
* announced after the commit, as every entry creation is.
|
||||
*
|
||||
* The journey's `photo_location` switch is not consulted: it decides whether
|
||||
* an existing entry without a place takes one from a photo added to it, and
|
||||
* these entries are written with their place from the start.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneyEntriesFromPhotosService {
|
||||
private readonly logger = new Logger(JourneyEntriesFromPhotosService.name);
|
||||
|
||||
constructor(
|
||||
private readonly journeys: JourneyDomainService,
|
||||
private readonly maps: MapsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository,
|
||||
@InjectRepository(JourneyEntryPhotos) private readonly entryPhotosRepo: JourneyEntryPhotosRepository,
|
||||
) {}
|
||||
|
||||
/** The journey's people may read it; only those who may edit it make entries. */
|
||||
private async requireEditable(journeyId: number, userId: number): Promise<void> {
|
||||
if (!(await this.journeys.canAccessJourney(journeyId, userId))) throw notFound('Journey not found');
|
||||
if (!(await this.journeys.canEdit(journeyId, userId))) throw forbidden('Not allowed');
|
||||
}
|
||||
|
||||
async preview(
|
||||
userId: number,
|
||||
journeyId: number,
|
||||
request: JourneyEntriesFromPhotosPreviewRequest,
|
||||
): Promise<JourneyEntriesFromPhotosPreviewResponse> {
|
||||
await this.requireEditable(journeyId, userId);
|
||||
const thresholds = {
|
||||
maxGapMinutes: request.maxGapMinutes ?? JOURNEY_FROM_PHOTOS_DEFAULT_GAP_MINUTES,
|
||||
maxDistanceKm: request.maxDistanceKm ?? JOURNEY_FROM_PHOTOS_DEFAULT_DISTANCE_KM,
|
||||
};
|
||||
const { captured, withoutTime } = capturedOf(await this.photosRepo.listOffEntries(journeyId));
|
||||
const summaries = clusterCaptures(localCaptures(captured, request.timezone ?? null), thresholds).map(
|
||||
summarizeCluster,
|
||||
);
|
||||
const names = await this.placeNames(summaries, request.lang);
|
||||
const clusters = summaries.map((summary, index): JourneyEntriesFromPhotosCluster => {
|
||||
const countryCode = countryOf(summary.lat, summary.lng);
|
||||
const placeName = names[index] ?? null;
|
||||
const fallback = fallbackTitle(countryCode, summary.date, request.lang);
|
||||
return {
|
||||
date: summary.date,
|
||||
startTime: summary.startTime,
|
||||
endTime: summary.endTime,
|
||||
timezone: summary.zone,
|
||||
lat: summary.lat,
|
||||
lng: summary.lng,
|
||||
countryCode,
|
||||
locationName: placeName,
|
||||
suggestedTitle: placeName ?? fallback.title,
|
||||
titleSource: placeName ? 'place' : fallback.source,
|
||||
photoIds: summary.photoIds,
|
||||
photoCount: summary.photoIds.length,
|
||||
coverPhotoId: summary.coverPhotoId,
|
||||
};
|
||||
});
|
||||
return { clusters, withoutCaptureTime: withoutTime, ...thresholds };
|
||||
}
|
||||
|
||||
/**
|
||||
* A place name for every group with a middle, from the geocoder, one point
|
||||
* asked once. Best effort: at most {@link FROM_PHOTOS_MAX_GEOCODED} points
|
||||
* and {@link FROM_PHOTOS_GEOCODE_BUDGET_MS} per preview, one after the other
|
||||
* so the geocoder's own rate limit is kept; a point it did not name (no
|
||||
* answer, an error, past the budget) gets null, and its group is named by
|
||||
* country or day instead.
|
||||
*/
|
||||
private async placeNames(summaries: readonly ClusterSummary[], lang: string | undefined): Promise<(string | null)[]> {
|
||||
const started = Date.now();
|
||||
const byPoint = new Map<string, string | null>();
|
||||
const names: (string | null)[] = [];
|
||||
for (const summary of summaries) {
|
||||
if (summary.lat === null || summary.lng === null) {
|
||||
names.push(null);
|
||||
continue;
|
||||
}
|
||||
// About a kilometre: two groups of the same town share one lookup.
|
||||
const key = `${summary.lat.toFixed(2)},${summary.lng.toFixed(2)}`;
|
||||
if (!byPoint.has(key)) {
|
||||
const withinBudget =
|
||||
byPoint.size < FROM_PHOTOS_MAX_GEOCODED && Date.now() - started < FROM_PHOTOS_GEOCODE_BUDGET_MS;
|
||||
byPoint.set(key, withinBudget ? await this.placeName(summary.lat, summary.lng, lang) : null);
|
||||
}
|
||||
names.push(byPoint.get(key) ?? null);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private async placeName(lat: number, lng: number, lang: string | undefined): Promise<string | null> {
|
||||
try {
|
||||
const where = await this.maps.reverseGeocode(String(lat), String(lng), lang, {
|
||||
lane: 'interactive',
|
||||
timeoutMs: GEOCODE_TIMEOUT_MS,
|
||||
locality: true,
|
||||
});
|
||||
const name = (where.name ?? '').trim();
|
||||
return name ? name.slice(0, 255) : null;
|
||||
} catch (err) {
|
||||
this.logger.warn(`place name for photos failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async create(
|
||||
userId: number,
|
||||
journeyId: number,
|
||||
request: JourneyEntriesFromPhotosCreateRequest,
|
||||
socketId?: string,
|
||||
): Promise<JourneyEntriesFromPhotosCreateResponse> {
|
||||
await this.requireEditable(journeyId, userId);
|
||||
|
||||
const done = await this.uow.transactional(async () => {
|
||||
// Read inside the transaction: a photo put on an entry since the preview is not on this list.
|
||||
const { captured } = capturedOf(await this.photosRepo.listOffEntries(journeyId));
|
||||
const captures = new Map<number, LocalCapture>(
|
||||
localCaptures(captured, request.timezone ?? null).map((capture) => [capture.id, capture]),
|
||||
);
|
||||
const claimed = new Set<number>();
|
||||
const skipped: number[] = [];
|
||||
const written: Array<{ entry: CreatedEntry; photoCount: number }> = [];
|
||||
for (const group of request.groups) {
|
||||
const photos: LocalCapture[] = [];
|
||||
for (const id of group.photoIds) {
|
||||
const capture = captures.get(id);
|
||||
if (!capture || claimed.has(id)) {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
claimed.add(id);
|
||||
photos.push(capture);
|
||||
}
|
||||
if (!photos.length) continue;
|
||||
const summary = summarizeCluster(photos);
|
||||
const countryCode = countryOf(summary.lat, summary.lng);
|
||||
const entry = await this.journeys.createEntry(
|
||||
journeyId,
|
||||
userId,
|
||||
{
|
||||
type: 'entry',
|
||||
title: group.title ?? fallbackTitle(countryCode, summary.date, request.lang).title,
|
||||
entry_date: summary.date,
|
||||
entry_time: summary.startTime,
|
||||
location_name: group.locationName || undefined,
|
||||
location_lat: summary.lat ?? undefined,
|
||||
location_lng: summary.lng ?? undefined,
|
||||
is_draft: true,
|
||||
},
|
||||
undefined,
|
||||
// Announced below, once every entry of the call is committed.
|
||||
false,
|
||||
);
|
||||
if (!entry) throw forbidden('Not allowed');
|
||||
const now = Date.now();
|
||||
for (const [index, photoId] of summary.photoIds.entries()) {
|
||||
await this.entryPhotosRepo.insertIgnore(entry.id, photoId, index, now);
|
||||
}
|
||||
written.push({ entry, photoCount: summary.photoIds.length });
|
||||
}
|
||||
return { written, skipped };
|
||||
});
|
||||
|
||||
for (const { entry } of done.written) {
|
||||
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry }, socketId);
|
||||
}
|
||||
return {
|
||||
entries: done.written.map(({ entry, photoCount }) => ({
|
||||
id: entry.id,
|
||||
title: entry.title ?? null,
|
||||
entry_date: entry.entry_date,
|
||||
entry_time: entry.entry_time ?? null,
|
||||
photoCount,
|
||||
})),
|
||||
skippedPhotoIds: [...new Set(done.skipped)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
journeyContributorRequestSchema,
|
||||
journeyContributorUpdateRequestSchema,
|
||||
journeyCreateRequestSchema,
|
||||
journeyEntriesFromPhotosCreateRequestSchema,
|
||||
journeyEntriesFromPhotosPreviewRequestSchema,
|
||||
journeyEntryCreateRequestSchema,
|
||||
journeyEntryPhotoUploadRequestSchema,
|
||||
journeyEntryUpdateRequestSchema,
|
||||
@@ -61,6 +63,9 @@ export class JourneyPhotosMoveDto extends createZodDto(journeyPhotosMoveRequestS
|
||||
export class JourneyEntryPhotoUploadDto extends createZodDto(journeyEntryPhotoUploadRequestSchema) {}
|
||||
export class JourneyGalleryPhotoUploadDto extends createZodDto(journeyGalleryPhotoUploadRequestSchema) {}
|
||||
export class JourneyGalleryVideoDto extends createZodDto(journeyGalleryVideoRequestSchema) {}
|
||||
/** Draft entries from gallery photos (#1920): strict, new routes with nothing older to keep answering. */
|
||||
export class JourneyEntriesFromPhotosPreviewDto extends createZodDto(journeyEntriesFromPhotosPreviewRequestSchema) {}
|
||||
export class JourneyEntriesFromPhotosCreateDto extends createZodDto(journeyEntriesFromPhotosCreateRequestSchema) {}
|
||||
|
||||
/** A Studio book save — the whole document, plus the version it was made against. */
|
||||
export class BookSaveDto extends createZodDto(bookSaveRequestSchema) {}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import { DawarichVisitSuggestions } from '../../../src/db/entities/DawarichVisit
|
||||
import { JourneyBookRevisions } from '../../../src/db/entities/JourneyBookRevisions.entity';
|
||||
import { JourneyBooks } from '../../../src/db/entities/JourneyBooks.entity';
|
||||
import { JourneyEntries } from '../../../src/db/entities/JourneyEntries.entity';
|
||||
import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity';
|
||||
import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
|
||||
import { TripJournalLinks } from '../../../src/db/entities/TripJournalLinks.entity';
|
||||
import { VacayHolidayCalendars } from '../../../src/db/entities/VacayHolidayCalendars.entity';
|
||||
import { VacayShares } from '../../../src/db/entities/VacayShares.entity';
|
||||
@@ -481,6 +483,35 @@ const journeyCases: ParityCase[] = [
|
||||
},
|
||||
expect: [{ event: 'journey:updated', user: 'actor' }],
|
||||
},
|
||||
{
|
||||
tool: 'create_journey_entries_from_photos',
|
||||
needs: ['journey'],
|
||||
setup: async (s, app) => {
|
||||
const photoId = await insertRow(ormOf(app), TrekPhotos, {
|
||||
provider: 'local',
|
||||
owner: s.owner.id,
|
||||
file_path: 'journey/p.jpg',
|
||||
taken_at: `${DAY}T09:00:00Z`,
|
||||
lat: 48.854,
|
||||
lng: 2.3326,
|
||||
});
|
||||
const galleryId = await insertRow(ormOf(app), JourneyPhotos, {
|
||||
journey: s.journey.id,
|
||||
photo: photoId,
|
||||
sort_order: 0,
|
||||
created_at: Date.now(),
|
||||
});
|
||||
keep(s, 'galleryFromPhoto', galleryId);
|
||||
},
|
||||
args: (s) => ({ journeyId: s.journey.id, groups: [{ photoIds: [kept(s, 'galleryFromPhoto')], title: 'Paris' }] }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => `/api/journeys/${s.journey.id}/entries/from-photos`,
|
||||
body: (s) => ({ groups: [{ photoIds: [kept(s, 'galleryFromPhoto')], title: 'Paris' }] }),
|
||||
},
|
||||
// One per draft written, after the commit.
|
||||
expect: [{ event: 'journey:entry:created', user: 'actor' }],
|
||||
},
|
||||
{
|
||||
tool: 'add_journey_contributor',
|
||||
needs: ['journey', 'member'],
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -235,6 +235,8 @@ Requires `journey:read` or `journey:write` scope.
|
||||
| `move_journey_photos` | Move photos of one entry to another entry of the same journey in one change. `keep_in_source: true` leaves them on the first entry too. A suggestion the photos land on becomes a written entry. |
|
||||
| `set_journey_photo_caption` | Set or clear (`null`) the caption of one gallery photo. Answers with the caption it replaced under `previous`. |
|
||||
| `delete_journey_photos` | Delete up to 100 photos or videos of one journey for good: they leave the gallery and every entry. A photo linked from Immich or Synology stays in that library. Every id must belong to the journey, or nothing is deleted. Needs the edit right on the journey. |
|
||||
| `preview_journey_entries_from_photos` | Group the gallery photos that are on no entry yet and know when they were taken into proposed entries, without writing anything: by local day, then split where two photos are more than `maxGapMinutes` (default 180) or two geotagged ones more than `maxDistanceKm` (default 20) apart. Each group comes with its date, times, middle and country, a suggested title (a place name, else the country, else the day) and its photo ids. Needs edit access to the journey. |
|
||||
| `create_journey_entries_from_photos` | Write the groups the traveller kept as draft entries with their photos, in one change, with the titles they chose. A photo put on an entry meanwhile, or named twice, is left out and listed in `skippedPhotoIds`; existing entries are never changed. |
|
||||
| `list_journey_contributors` | List the contributors of a journey (owner and editors/viewers). |
|
||||
| `add_journey_contributor` | Invite a user to a journey with `editor` or `viewer` role. |
|
||||
| `update_journey_contributor_role` | Change a contributor's role between `editor` and `viewer`. The owner's own role cannot be changed. |
|
||||
|
||||
Reference in New Issue
Block a user