diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index 7a6a083e2..c6f4db854 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -11,7 +11,7 @@ "src/nest/collections/collections.service.ts": 1478, "src/nest/doc-sync/doc-sync.service.ts": 1060, "src/nest/doc-sync/providers/synology-drive.client.ts": 1160, - "src/nest/journey/journey-domain.service.ts": 1799, + "src/nest/journey/journey-domain.service.ts": 1785, "src/nest/places/places.service.ts": 1592, "src/nest/plugins/plugin-runtime.service.ts": 1463, "src/nest/plugins/runtime/plugin-sdk.ts": 1093, diff --git a/server/src/db/entities/JourneyShareTokens.entity.ts b/server/src/db/entities/JourneyShareTokens.entity.ts index f38899e15..794d139af 100644 --- a/server/src/db/entities/JourneyShareTokens.entity.ts +++ b/server/src/db/entities/JourneyShareTokens.entity.ts @@ -16,6 +16,8 @@ export class JourneyShareTokens { share_map?: number | null = 1; created_at?: string | null; newest_first: number & Opt = 0; + share_plan: number & Opt = 0; + share_recordings: number & Opt = 0; createdByRef!: Ref; } @@ -34,6 +36,8 @@ export const JourneyShareTokensSchema = defineEntity({ share_map: p.integer().nullable(), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), newest_first: p.integer().default(0), + share_plan: p.integer().default(0), + share_recordings: p.integer().default(0), createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').hidden().index('idx_journey_share_tokens_created_by'), }, }); diff --git a/server/src/db/kysely/JourneyShareTokens.table.ts b/server/src/db/kysely/JourneyShareTokens.table.ts index e110c0a90..16841e46b 100644 --- a/server/src/db/kysely/JourneyShareTokens.table.ts +++ b/server/src/db/kysely/JourneyShareTokens.table.ts @@ -12,4 +12,6 @@ export interface JourneyShareTokensTable { share_map: InsertOptional; created_at: InsertOptional; newest_first: InsertOptional; + share_plan: InsertOptional; + share_recordings: InsertOptional; } diff --git a/server/src/db/migrations/Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings.ts b/server/src/db/migrations/Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings.ts new file mode 100644 index 000000000..de395c600 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings.ts @@ -0,0 +1,26 @@ +import { addColumnIfMissing } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * JRN-04: a journey's public link can also show the trips' plan and the + * recorded days on its map. + * + * `share_plan` puts the places of the linked trips (and their GPX tracks) on + * the public map, `share_recordings` the days of route the journey keeps. + * Both are off by default, so a journey that is public already shows exactly + * what it showed before this step, and neither shows anything while the map + * itself is not shared. + */ +export class Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings extends Migration { + override name = 'Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings'; + + override async up(): Promise { + await addColumnIfMissing(this, 'journey_share_tokens', 'share_plan', 'share_plan INTEGER NOT NULL DEFAULT 0'); + await addColumnIfMissing( + this, + 'journey_share_tokens', + 'share_recordings', + 'share_recordings INTEGER NOT NULL DEFAULT 0', + ); + } +} diff --git a/server/src/db/repositories/JourneyEntryStays.repository.ts b/server/src/db/repositories/JourneyEntryStays.repository.ts index f1d4a6c24..aecf80c8d 100644 --- a/server/src/db/repositories/JourneyEntryStays.repository.ts +++ b/server/src/db/repositories/JourneyEntryStays.repository.ts @@ -20,6 +20,17 @@ export interface JourneyEntryStayWrite { user_id: number; } +/** A located stay of a journey, as its map draws it (JRN-04). */ +export interface JourneyEntryStayMapRow { + id: number; + entry_id: number; + name: string; + lat: number; + lng: number; + started_at: string; + ended_at: string; +} + /** A stay a journey holds, with the entry that holds it. */ interface JourneyEntryStayHeld { source_visit_id: string; @@ -60,4 +71,18 @@ export class JourneyEntryStaysRepository extends TrekRepository { + const rows = await this.db() + .selectFrom('journey_entry_stays as s') + .select(['s.id', 's.entry_id', 's.name', 's.lat', 's.lng', 's.started_at', 's.ended_at']) + .where('s.journey_id', '=', journeyId) + .where('s.lat', 'is not', null) + .where('s.lng', 'is not', null) + .orderBy('s.entry_id', 'asc') + .orderBy('s.sort_order', 'asc') + .execute(); + return rows.map((row) => ({ ...row, lat: row.lat as number, lng: row.lng as number })); + } } diff --git a/server/src/db/repositories/JourneyShareTokens.repository.ts b/server/src/db/repositories/JourneyShareTokens.repository.ts index 42d3559ae..a38cb2820 100644 --- a/server/src/db/repositories/JourneyShareTokens.repository.ts +++ b/server/src/db/repositories/JourneyShareTokens.repository.ts @@ -8,6 +8,8 @@ export interface JourneyShareLinkFlagsRow { share_gallery: number | null; share_map: number | null; newest_first: number; + share_plan: number; + share_recordings: number; } /** JS4/JS11's full-row shape (`getJourneyShareLink`, `getPublicJourney`'s entrypoint read). */ @@ -21,6 +23,18 @@ export interface JourneyShareTokenRow { share_map: number | null; created_at: string | null; newest_first: number; + share_plan: number; + share_recordings: number; +} + +/** Every flag of a link, as stored (0/1). */ +export interface JourneyShareFlags { + share_timeline: number; + share_gallery: number; + share_map: number; + newest_first: number; + share_plan: number; + share_recordings: number; } /** JS6/JS9's narrow token-lookup projection — the anonymous photo/asset validators. */ @@ -82,7 +96,15 @@ export class JourneyShareTokensRepository extends TrekRepository { return await this.qb('jst') - .select(['jst.token', 'jst.share_timeline', 'jst.share_gallery', 'jst.share_map', 'jst.newest_first']) + .select([ + 'jst.token', + 'jst.share_timeline', + 'jst.share_gallery', + 'jst.share_map', + 'jst.newest_first', + 'jst.share_plan', + 'jst.share_recordings', + ]) .where({ journey: journeyId }) .execute('get', false); } @@ -90,25 +112,17 @@ export class JourneyShareTokensRepository extends TrekRepository { + async updateFlags(journeyId: number, flags: JourneyShareFlags): Promise { await this.nativeUpdate({ journey: journeyId }, flags); } /** JS3 — the create branch: `INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?,?,?,?,?,?,?)`. */ - async insertLink( - journeyId: number, - token: string, - createdBy: number, - flags: { share_timeline: number; share_gallery: number; share_map: number; newest_first: number }, - ): Promise { + async insertLink(journeyId: number, token: string, createdBy: number, flags: JourneyShareFlags): Promise { await this.insert({ journey: journeyId, token, createdByRef: createdBy, ...flags }); } diff --git a/server/src/db/repositories/JourneyTrips.repository.ts b/server/src/db/repositories/JourneyTrips.repository.ts index d8d377767..622ef2ce4 100644 --- a/server/src/db/repositories/JourneyTrips.repository.ts +++ b/server/src/db/repositories/JourneyTrips.repository.ts @@ -48,6 +48,32 @@ export interface AssignmentTimeRow { /** The `places`/`day_assignments`/`days` tables the sync-engine reads read. */ type SyncPlacesKyselyDB = Pick; +/** One day a linked trip's plan puts a located place on (JRN-04), {@link JourneyTripsRepository.listMapPlacesForJourney}. */ +export interface JourneyMapPlaceRow { + place_id: number; + trip_id: number; + trip_title: string; + name: string; + lat: number; + lng: number; + day_date: string | null; + time: string | null; + category_color: string | null; + category_icon: string | null; +} + +/** A place of a linked trip that carries a route (JRN-04), {@link JourneyTripsRepository.listRouteSourcesForJourney}. */ +export interface JourneyRouteSourceRow { + place_id: number; + trip_id: number; + name: string; + route_color: string | null; + route_geometry: string; +} + +/** The tables the journey map's plan reads join. */ +type JourneyMapKyselyDB = Pick; + /** * `journey_trips` — a genuine TWO-column composite primary key (`journey` + * `trip`, both `.primary()`, R3 — pinned against @@ -180,4 +206,70 @@ export class JourneyTripsRepository extends TrekRepository { .execute(); return rows as AssignmentTimeRow[]; } + + /** + * The located places the linked trips plan on a day, one row per day they + * stand on, in plan order (JRN-04). Through `journey_trips`, so a linked + * trip nobody has written about yet still shows its plan; a place without + * coordinates is left out rather than put anywhere. + */ + async listMapPlacesForJourney(journeyId: number): Promise { + const rows = await this.kysely() + .selectFrom('journey_trips as jt') + .innerJoin('trips as t', 't.id', 'jt.trip_id') + .innerJoin('places as p', 'p.trip_id', 'jt.trip_id') + .innerJoin('day_assignments as da', 'da.place_id', 'p.id') + .innerJoin('days as d', 'd.id', 'da.day_id') + .leftJoin('categories as c', 'c.id', 'p.category_id') + .select([ + 'p.id as place_id', + 'p.trip_id', + 't.title as trip_title', + 'p.name', + 'p.lat', + 'p.lng', + 'd.date as day_date', + 'da.assignment_time', + 'p.place_time', + 'c.color as category_color', + 'c.icon as category_icon', + ]) + .where('jt.journey_id', '=', journeyId) + .where('p.lat', 'is not', null) + .where('p.lng', 'is not', null) + .orderBy('t.start_date', 'asc') + .orderBy('d.day_number', 'asc') + .orderBy('da.order_index', 'asc') + .execute(); + return rows.map((row) => ({ + place_id: row.place_id, + trip_id: row.trip_id, + trip_title: row.trip_title, + name: row.name, + lat: row.lat as number, + lng: row.lng as number, + day_date: row.day_date, + time: row.assignment_time ?? row.place_time, + category_color: row.category_color, + category_icon: row.category_icon, + })); + } + + /** + * The places of the linked trips that carry a route (JRN-04). Unlike the + * entries' `listTracksSource`, which `/tracks` and Studio read and which + * stays as it is, this goes through `journey_trips`. + */ + async listRouteSourcesForJourney(journeyId: number): Promise { + const rows = await this.kysely() + .selectFrom('journey_trips as jt') + .innerJoin('places as p', 'p.trip_id', 'jt.trip_id') + .select(['p.id as place_id', 'p.trip_id', 'p.name', 'p.route_color', 'p.route_geometry']) + .where('jt.journey_id', '=', journeyId) + .where('p.route_geometry', 'is not', null) + .orderBy('p.trip_id', 'asc') + .orderBy('p.id', 'asc') + .execute(); + return rows as JourneyRouteSourceRow[]; + } } diff --git a/server/src/nest/common/validate-route-guards.ts b/server/src/nest/common/validate-route-guards.ts index 79d4891db..6af8cec1d 100644 --- a/server/src/nest/common/validate-route-guards.ts +++ b/server/src/nest/common/validate-route-guards.ts @@ -130,6 +130,7 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [ // Share-token validated. 'JourneyPublicController.get', 'JourneyPublicController.legacyPhoto', + 'JourneyPublicController.mapLayers', 'JourneyPublicController.photo', // The MCP transport — bearer tokens are verified inside the handler. // The same documents under the resource URL, for clients that append the diff --git a/server/src/nest/journey/journey-domain.module.ts b/server/src/nest/journey/journey-domain.module.ts index 2f97b3993..9a3feb266 100644 --- a/server/src/nest/journey/journey-domain.module.ts +++ b/server/src/nest/journey/journey-domain.module.ts @@ -16,6 +16,7 @@ import { RealtimeModule } from '../realtime/realtime.module'; import { SettingsModule } from '../settings/settings.module'; import { JourneyDomainService } from './journey-domain.service'; import { JourneyEntryStaysService } from './journey-entry-stays.service'; +import { JourneyMapService } from './journey-map.service'; import { JourneyRecordedDaysService } from './journey-recorded-days.service'; import { JourneyRecordingPrepService } from './journey-recording-prep.service'; import { JourneyShareService } from './journey-share.service'; @@ -75,6 +76,9 @@ import { Module } from '@nestjs/common'; * `JourneyRecordingPrep` (JRN-03) is how far preparing a journey's recorded * days got for each person; `JourneyRecordingPrepService` keeps it and tells * the Dawarich sync which journeys to read. + * `JourneyMapService` (JRN-04) reads what the journey map shows besides its + * entries and photos, for the journey's people and for its share link, from + * the tables already registered here. */ @Module({ imports: [ @@ -103,6 +107,7 @@ import { Module } from '@nestjs/common'; JourneyRecordedDaysService, JourneyEntryStaysService, JourneyRecordingPrepService, + JourneyMapService, ], exports: [ JourneyDomainService, @@ -110,6 +115,7 @@ import { Module } from '@nestjs/common'; JourneyRecordedDaysService, JourneyEntryStaysService, JourneyRecordingPrepService, + JourneyMapService, ], }) export class JourneyDomainModule {} diff --git a/server/src/nest/journey/journey-domain.service.ts b/server/src/nest/journey/journey-domain.service.ts index 364bfdf3e..f4a922182 100644 --- a/server/src/nest/journey/journey-domain.service.ts +++ b/server/src/nest/journey/journey-domain.service.ts @@ -28,6 +28,7 @@ import type { TripsRepository } from '../../db/repositories/Trips.repository'; import { Places } from '../../db/entities/Places.entity'; import type { PlacesRepository } from '../../db/repositories/Places.repository'; import { presenceSet } from '../../db/repositories/_shared/presence-set'; +import { parseRouteGeometry } from './journey-geometry'; /** * English country names for whatever codes a journey turned up. @@ -914,25 +915,10 @@ export class JourneyDomainService { const tracks: JourneyTrack[] = []; for (const row of rows) { - let parsed: unknown; - try { - parsed = JSON.parse(row.route_geometry); - } catch { - continue; // A geometry that is not JSON is not worth failing the whole map over. - } - if (!Array.isArray(parsed)) continue; - - const points: [number, number][] = []; - for (const entry of parsed) { - if (!Array.isArray(entry) || entry.length < 2) continue; - const lat = Number(entry[0]); - const lng = Number(entry[1]); - if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue; - points.push([lat, lng]); - } - // A single point is a pin, not a line, and the map already has the entry markers. - if (points.length < 2) continue; - + // A geometry that is not JSON, or a single point (a pin, not a line), is + // not worth failing the whole map over. + const points = parseRouteGeometry(row.route_geometry); + if (!points) continue; tracks.push({ place_id: row.place_id, trip_id: row.trip_id, diff --git a/server/src/nest/journey/journey-geometry.ts b/server/src/nest/journey/journey-geometry.ts new file mode 100644 index 000000000..fe927c98f --- /dev/null +++ b/server/src/nest/journey/journey-geometry.ts @@ -0,0 +1,36 @@ +/** A coordinate pair that is a place on Earth: finite, and within latitude and longitude. */ +export function isValidGeoPoint(lat: unknown, lng: unknown): lat is number { + return ( + typeof lat === 'number' && + typeof lng === 'number' && + Number.isFinite(lat) && + Number.isFinite(lng) && + Math.abs(lat) <= 90 && + Math.abs(lng) <= 180 + ); +} + +/** + * A place's stored route geometry as `[lat, lng]` points, the way the GPX + * importer wrote it; elevation, where kept, is dropped. Points that are not + * numbers are skipped, and a text that is not JSON, or that leaves fewer than + * two points, is no line: null, so one broken geometry never fails a map. + */ +export function parseRouteGeometry(text: string): [number, number][] | null { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return null; + } + if (!Array.isArray(parsed)) return null; + const points: [number, number][] = []; + for (const entry of parsed) { + if (!Array.isArray(entry) || entry.length < 2) continue; + const lat = Number(entry[0]); + const lng = Number(entry[1]); + if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue; + points.push([lat, lng]); + } + return points.length < 2 ? null : points; +} diff --git a/server/src/nest/journey/journey-map.controller.ts b/server/src/nest/journey/journey-map.controller.ts new file mode 100644 index 000000000..189c76095 --- /dev/null +++ b/server/src/nest/journey/journey-map.controller.ts @@ -0,0 +1,29 @@ +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 { JourneyMapService } from './journey-map.service'; +import { Controller, Get, Param, UseGuards } from '@nestjs/common'; +import { journeyMapLayersResponseSchema } from '@trek/shared'; + +/** + * GET /api/journeys/:id/map-layers (JRN-04): the plan, the routes and the + * stays the journey map can show beside its entries, each source answering on + * its own. Read-only and derived, like `/tracks`; the journey's own access + * applies, a stranger gets the same 404 as for the journey itself. + */ +@Controller('api/journeys') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.JOURNEY, 'Journey') +export class JourneyMapController { + constructor(private readonly map: JourneyMapService) {} + + @Get(':id/map-layers') + @ResponseContract(journeyMapLayersResponseSchema) + async layers(@CurrentUser() user: User, @Param('id') id: string) { + return this.map.mapLayers(Number(id), user.id); + } +} diff --git a/server/src/nest/journey/journey-map.mcp.ts b/server/src/nest/journey/journey-map.mcp.ts new file mode 100644 index 000000000..8978de3be --- /dev/null +++ b/server/src/nest/journey/journey-map.mcp.ts @@ -0,0 +1,49 @@ +import { ADDON_IDS } from '../../addons'; +import { McpController, TOOL_ANNOTATIONS_READONLY, Tool, ok, type McpContext } from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { JourneyMapService } from './journey-map.service'; +import { idSchema, type JourneyMapLayerResult } from '@trek/shared'; + +const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY); + +/** + * The journey map's layers (JRN-04) over MCP: the same service and the same + * journey access as GET `/api/journeys/:id/map-layers`. The places and stays + * come with their positions; a route answers with its name and size, never + * its geometry. + */ +@McpController() +export class JourneyMapMcp { + constructor( + private readonly map: JourneyMapService, + readonly addons: AddonsService, + ) {} + + @Tool({ + name: 'get_journey_map_layers', + description: + "What a journey's map shows besides its entries and photos: the planned places of its linked trips (with the days the plan puts each on and, when one exists, the journal entry written about it; a planned place alone is no proof of a visit), the GPX routes of those trips while the journey's track switch is on, and the stays journal entries were taken over from (several per day report, each where it was recorded). Each source answers ok, or unavailable when it could not be read. The recorded days are listed by list_journey_recorded_days.", + inputSchema: { journeyId: idSchema }, + annotations: TOOL_ANNOTATIONS_READONLY, + when: journeyAddonOn, + access: { group: 'journey', mode: 'read' }, + }) + async getJourneyMapLayers({ journeyId }: { journeyId: number }, ctx: McpContext) { + const layers = await this.map.mapLayers(journeyId, ctx.userId); + return ok({ + places: layers.places, + routes: mapItems(layers.routes, (route) => ({ + place_id: route.place_id, + trip_id: route.trip_id, + name: route.name, + points: route.points.length, + })), + stays: layers.stays, + }); + } +} + +function mapItems(layer: JourneyMapLayerResult, as: (item: T) => U): JourneyMapLayerResult { + return layer.status === 'ok' ? { status: 'ok', items: layer.items.map(as) } : layer; +} diff --git a/server/src/nest/journey/journey-map.service.ts b/server/src/nest/journey/journey-map.service.ts new file mode 100644 index 000000000..30d7a8685 --- /dev/null +++ b/server/src/nest/journey/journey-map.service.ts @@ -0,0 +1,188 @@ +import { JourneyEntries } from '../../db/entities/JourneyEntries.entity'; +import { JourneyEntryStays } from '../../db/entities/JourneyEntryStays.entity'; +import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity'; +import { JourneyTrips } from '../../db/entities/JourneyTrips.entity'; +import { Journeys } from '../../db/entities/Journeys.entity'; +import type { JourneyEntriesRepository } from '../../db/repositories/JourneyEntries.repository'; +import type { JourneyEntryStaysRepository } from '../../db/repositories/JourneyEntryStays.repository'; +import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository'; +import type { JourneyTripsRepository } from '../../db/repositories/JourneyTrips.repository'; +import type { JourneysRepository } from '../../db/repositories/Journeys.repository'; +import { logWarn } from '../audit/audit-log.logger'; +import { notFound } from '../common/domain-error'; +import { JourneyDomainService } from './journey-domain.service'; +import { isValidGeoPoint, parseRouteGeometry } from './journey-geometry'; +import { JourneyRecordedDaysService } from './journey-recorded-days.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { + JourneyMapLayerResult, + JourneyMapLayersResponse, + JourneyMapPlace, + JourneyMapRecording, + JourneyMapStay, + JourneyPublicMapLayersResponse, + JourneyTrack, +} from '@trek/shared'; + +/** The entries a map may tie its plan and its stays to: who can read them is decided by the caller. */ +interface EntryRef { + id: number; + source_place_id?: number | null; + entry_date: string; + type: string; +} + +const WITHHELD = { status: 'withheld' } as const; + +/** + * What the journey map shows besides its entries and photos (JRN-04): the plan + * of the linked trips, their GPX routes, the days of route the journey keeps + * and the stays its entries were taken over from. + * + * Every source is read on its own, and one that fails answers `unavailable` + * while the others still draw. Nothing is stored here and nothing is written: + * a layer switched on in a browser only ever hides what the reader may see. + * The public answer is cut on the server, by the link's flags, never by the + * client: the map switched off shares nothing of it. + */ +@Injectable() +export class JourneyMapService { + constructor( + private readonly journeys: JourneyDomainService, + private readonly recordedDays: JourneyRecordedDaysService, + @InjectRepository(JourneyTrips) private readonly tripsRepo: JourneyTripsRepository, + @InjectRepository(JourneyEntries) private readonly entriesRepo: JourneyEntriesRepository, + @InjectRepository(JourneyEntryStays) private readonly staysRepo: JourneyEntryStaysRepository, + @InjectRepository(JourneyShareTokens) private readonly shareTokensRepo: JourneyShareTokensRepository, + @InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository, + ) {} + + /** The map layers of a journey for one of its people: the owner or a contributor. */ + async mapLayers(journeyId: number, userId: number): Promise { + const journey = await this.journeys.canAccessJourney(journeyId, userId); + if (!journey) throw notFound('Journey not found'); + const entries = await this.entriesRepo.listForJourney(journeyId); + // A skeleton is the plan mirrored into the timeline, not something written. + const written = entries.filter((entry) => entry.type !== 'skeleton'); + const [places, routes, stays] = await Promise.all([ + this.layer('places', journeyId, () => this.places(journeyId, written)), + this.layer('routes', journeyId, () => (journey.show_trip_tracks ? this.routes(journeyId) : Promise.resolve([]))), + this.layer('stays', journeyId, () => this.stays(journeyId, written)), + ]); + return { places, routes, stays }; + } + + /** + * The map layers a share link shows, null for a link that does not exist. + * Drafts never reach it: the entries it ties places and stays to are the + * published ones, and a recorded day shows only beside a published entry. + */ + async publicMapLayers(token: string): Promise { + const link = await this.shareTokensRepo.findByToken(token); + if (!link) return null; + const journey = await this.journeysRepo.findById(link.journey_id); + if (!journey) return null; + if (!link.share_map) return { places: WITHHELD, routes: WITHHELD, stays: WITHHELD, recordings: WITHHELD }; + + const journeyId = link.journey_id; + const published = await this.entriesRepo.listPublicEntries(journeyId); + const sharePlan = !!link.share_plan; + const [places, routes, stays, recordings] = await Promise.all([ + sharePlan ? this.layer('places', journeyId, () => this.places(journeyId, published)) : WITHHELD, + sharePlan && journey.show_trip_tracks ? this.layer('routes', journeyId, () => this.routes(journeyId)) : WITHHELD, + this.layer('stays', journeyId, () => this.stays(journeyId, published)), + link.share_recordings + ? this.layer('recordings', journeyId, () => this.recordings(journeyId, published)) + : WITHHELD, + ]); + return { places, routes, stays, recordings }; + } + + private async layer(name: string, journeyId: number, read: () => Promise): Promise> { + try { + return { status: 'ok', items: await read() }; + } catch (err) { + logWarn(`[journey-map] the ${name} of journey ${journeyId} could not be read: ${(err as Error).message}`); + return { status: 'unavailable' }; + } + } + + /** + * One pin per planned place, with every day the plan puts it on. A place an + * entry came from points at that entry, the earliest one when several did, + * so the map can show plan and memory as one; a plan alone proves no visit. + */ + private async places(journeyId: number, entries: EntryRef[]): Promise { + const rows = await this.tripsRepo.listMapPlacesForJourney(journeyId); + const entryByPlace = new Map(); + for (const entry of [...entries].sort((a, b) => a.entry_date.localeCompare(b.entry_date))) { + if (entry.source_place_id != null && !entryByPlace.has(entry.source_place_id)) { + entryByPlace.set(entry.source_place_id, entry.id); + } + } + const byPlace = new Map(); + for (const row of rows) { + if (!isValidGeoPoint(row.lat, row.lng)) continue; + const known = byPlace.get(row.place_id); + if (known) { + if (row.day_date && !known.days.includes(row.day_date)) known.days.push(row.day_date); + continue; + } + byPlace.set(row.place_id, { + place_id: row.place_id, + trip_id: row.trip_id, + trip_title: row.trip_title, + name: row.name, + lat: row.lat, + lng: row.lng, + days: row.day_date ? [row.day_date] : [], + time: row.time, + category_color: row.category_color, + category_icon: row.category_icon, + entry_id: entryByPlace.get(row.place_id) ?? null, + }); + } + for (const place of byPlace.values()) place.days.sort(); + return [...byPlace.values()]; + } + + private async routes(journeyId: number): Promise { + const tracks: JourneyTrack[] = []; + for (const row of await this.tripsRepo.listRouteSourcesForJourney(journeyId)) { + const points = parseRouteGeometry(row.route_geometry); + if (!points) continue; + tracks.push({ + place_id: row.place_id, + trip_id: row.trip_id, + name: row.name, + color: row.route_color, + points, + kind: 'trip_gpx', + }); + } + return tracks; + } + + /** The located stays of the given entries, each where it was recorded; one without a place is left out. */ + private async stays(journeyId: number, entries: EntryRef[]): Promise { + const visible = new Set(entries.map((entry) => entry.id)); + return (await this.staysRepo.listLocatedForJourney(journeyId)).filter( + (stay) => visible.has(stay.entry_id) && isValidGeoPoint(stay.lat, stay.lng), + ); + } + + /** The kept days that have one of the given entries on them, their pieces apart. */ + private async recordings(journeyId: number, entries: EntryRef[]): Promise { + const days = new Set(entries.map((entry) => entry.entry_date)); + return (await this.recordedDays.list(journeyId)) + .filter((day) => days.has(day.date)) + .map((day) => ({ + date: day.date, + pieces: day.segments + .map((segment) => segment.points.filter(([lat, lng]) => isValidGeoPoint(lat, lng))) + .filter((points) => points.length > 1), + distance_m: day.stats.distanceMeters, + })); + } +} diff --git a/server/src/nest/journey/journey-public.controller.ts b/server/src/nest/journey/journey-public.controller.ts index 351c63b45..5331cb7e9 100644 --- a/server/src/nest/journey/journey-public.controller.ts +++ b/server/src/nest/journey/journey-public.controller.ts @@ -2,9 +2,11 @@ import { ADDON_IDS } from '../../addons'; import { AddonGuard } from '../addons/addon.guard'; import { RequireAddon } from '../addons/require-addon.decorator'; import { Public } from '../auth-core/public.decorator'; +import { ResponseContract } from '../common/response-contract'; import { StorageService } from '../storage/storage.service'; import { JourneyService } from './journey.service'; import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common'; +import { journeyPublicMapLayersResponseSchema } from '@trek/shared'; import type { Response } from 'express'; import path from 'node:path'; @@ -42,6 +44,20 @@ export class JourneyPublicController { return data; } + /** + * What the shared map shows beside the entries and photos (JRN-04), cut to + * the link's flags on the server: nothing while the map is not shared. + */ + @Get(':token/map-layers') + @ResponseContract(journeyPublicMapLayersResponseSchema) + async mapLayers(@Param('token') token: string) { + const layers = await this.journey.getPublicMapLayers(token); + if (!layers) { + throw new HttpException({ error: 'Not found' }, 404); + } + return layers; + } + @Get(':token/photos/:photoId/:kind') async photo( @Param('token') token: string, diff --git a/server/src/nest/journey/journey-share.service.ts b/server/src/nest/journey/journey-share.service.ts index 3369d8bed..afd6d3717 100644 --- a/server/src/nest/journey/journey-share.service.ts +++ b/server/src/nest/journey/journey-share.service.ts @@ -26,6 +26,10 @@ interface JourneySharePermissions { share_map?: boolean; /** Read the journey newest-first, like a blog, rather than in trip order. */ newest_first?: boolean; + /** The trips' plan on the shared map (JRN-04); off unless asked for. */ + share_plan?: boolean; + /** The recorded days on the shared map (JRN-04); off unless asked for. */ + share_recordings?: boolean; } interface JourneyShareTokenInfo { @@ -35,6 +39,8 @@ interface JourneyShareTokenInfo { share_gallery: boolean; share_map: boolean; newest_first: boolean; + share_plan: boolean; + share_recordings: boolean; } /** @@ -105,19 +111,30 @@ export class JourneyShareService { const share_gallery = permissions.share_gallery ?? !!existing.share_gallery; const share_map = permissions.share_map ?? !!existing.share_map; const newest_first = permissions.newest_first ?? !!existing.newest_first; + const share_plan = permissions.share_plan ?? !!existing.share_plan; + const share_recordings = permissions.share_recordings ?? !!existing.share_recordings; // JS2 — the SERVICE resolves the final value of every flag (above); the - // repository writes exactly those four already-resolved booleans, a - // plain 4-column UPDATE, not a presence-sentinel one. + // repository writes exactly those already-resolved booleans, a plain + // UPDATE, not a presence-sentinel one. await this.shareTokensRepo.updateFlags(journeyId, { share_timeline: share_timeline ? 1 : 0, share_gallery: share_gallery ? 1 : 0, share_map: share_map ? 1 : 0, newest_first: newest_first ? 1 : 0, + share_plan: share_plan ? 1 : 0, + share_recordings: share_recordings ? 1 : 0, }); return { token: existing.token, created: false }; } - const { share_timeline = true, share_gallery = true, share_map = true, newest_first = false } = permissions; + const { + share_timeline = true, + share_gallery = true, + share_map = true, + newest_first = false, + share_plan = false, + share_recordings = false, + } = permissions; const token = crypto.randomBytes(24).toString('base64url'); // JS3. @@ -126,6 +143,8 @@ export class JourneyShareService { share_gallery: share_gallery ? 1 : 0, share_map: share_map ? 1 : 0, newest_first: newest_first ? 1 : 0, + share_plan: share_plan ? 1 : 0, + share_recordings: share_recordings ? 1 : 0, }); return { token, created: true }; }); @@ -160,6 +179,8 @@ export class JourneyShareService { share_gallery: !!row.share_gallery, share_map: !!row.share_map, newest_first: !!row.newest_first, + share_plan: !!row.share_plan, + share_recordings: !!row.share_recordings, }; } diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts index c7ab4e1f2..2b5dfb612 100644 --- a/server/src/nest/journey/journey.controller.ts +++ b/server/src/nest/journey/journey.controller.ts @@ -848,6 +848,8 @@ export class JourneyController { share_gallery: body.share_gallery as boolean | undefined, share_map: body.share_map as boolean | undefined, newest_first: body.newest_first as boolean | undefined, + share_plan: body.share_plan, + share_recordings: body.share_recordings, }); if (!result) { throw new HttpException({ error: 'Not allowed' }, 403); diff --git a/server/src/nest/journey/journey.mcp.ts b/server/src/nest/journey/journey.mcp.ts index e431adafe..59c669868 100644 --- a/server/src/nest/journey/journey.mcp.ts +++ b/server/src/nest/journey/journey.mcp.ts @@ -17,7 +17,7 @@ import { AddonsService } from '../addons/addons.service'; import { JourneyDomainService } from './journey-domain.service'; import { JourneyPhotoCaptureService } from './journey-photo-capture.service'; import { JourneyShareService } from './journey-share.service'; -import { idSchema, journeyUpdateRequestSchema } from '@trek/shared'; +import { idSchema, journeyShareLinkRequestSchema, journeyUpdateRequestSchema } from '@trek/shared'; import { z } from 'zod'; @@ -780,13 +780,15 @@ export class JourneyMcp { @Tool({ name: 'create_journey_share_link', description: - 'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on.', + 'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on and plan/recordings off. share_plan puts the planned places and GPX tracks on the shared map, share_recordings the recorded days that have a published entry; neither shows anything while share_map is off.', inputSchema: { journeyId: idSchema, share_timeline: z.boolean().optional(), share_gallery: z.boolean().optional(), share_map: z.boolean().optional(), newest_first: z.boolean().optional(), + share_plan: journeyShareLinkRequestSchema.shape.share_plan, + share_recordings: journeyShareLinkRequestSchema.shape.share_recordings, }, annotations: TOOL_ANNOTATIONS_WRITE, when: journeyAddonOn, @@ -802,6 +804,8 @@ export class JourneyMcp { share_gallery?: boolean; share_map?: boolean; newest_first?: boolean; + share_plan?: boolean; + share_recordings?: boolean; }, ctx: McpContext, ) { diff --git a/server/src/nest/journey/journey.module.ts b/server/src/nest/journey/journey.module.ts index e20c15237..4a4d19e40 100644 --- a/server/src/nest/journey/journey.module.ts +++ b/server/src/nest/journey/journey.module.ts @@ -10,6 +10,8 @@ import { StorageModule } from '../storage/storage.module'; import { StorageService } from '../storage/storage.service'; import { JourneyBookService } from './journey-book.service'; import { JourneyDomainModule } from './journey-domain.module'; +import { JourneyMapController } from './journey-map.controller'; +import { JourneyMapMcp } from './journey-map.mcp'; import { JourneyPhotoCaptureModule } from './journey-photo-capture.module'; import { JourneyPublicController } from './journey-public.controller'; import { JourneyController } from './journey.controller'; @@ -50,7 +52,7 @@ import { MulterModule } from '@nestjs/platform-express'; // for its own providers only, per that module's own docstring). MikroOrmModule.forFeature([Users, JourneyBooks]), ], - controllers: [JourneyController, JourneyPublicController], - providers: [JourneyService, JourneyBookService, JourneyMcp], + controllers: [JourneyController, JourneyMapController, JourneyPublicController], + providers: [JourneyService, JourneyBookService, JourneyMcp, JourneyMapMcp], }) export class JourneyModule {} diff --git a/server/src/nest/journey/journey.service.ts b/server/src/nest/journey/journey.service.ts index fa227724b..6f1049f6d 100644 --- a/server/src/nest/journey/journey.service.ts +++ b/server/src/nest/journey/journey.service.ts @@ -5,6 +5,7 @@ import { ImmichService } from '../memories/immich.service'; import { PhotoProviderRegistry } from '../memories/photo-provider.registry'; import { PhotoResolverService } from '../memories/photo-resolver.service'; import { JourneyDomainService } from './journey-domain.service'; +import { JourneyMapService } from './journey-map.service'; import { JourneyShareService } from './journey-share.service'; import { Injectable } from '@nestjs/common'; @@ -26,6 +27,7 @@ export class JourneyService { private readonly journey: JourneyDomainService, private readonly share: JourneyShareService, private readonly immichRepo: UserImmichRepository, + private readonly map: JourneyMapService, ) {} async journeyAddonEnabled(): Promise { @@ -198,6 +200,9 @@ export class JourneyService { async getPublicJourney(token: string) { return this.share.getPublicJourney(token); } + getPublicMapLayers(token: string) { + return this.map.publicMapLayers(token); + } validateShareTokenForPhoto(token: string, photoId: number) { return this.share.validateShareTokenForPhoto(token, photoId); } diff --git a/server/tests/e2e/journey.e2e.test.ts b/server/tests/e2e/journey.e2e.test.ts index 26c33ec50..28bfac82d 100644 --- a/server/tests/e2e/journey.e2e.test.ts +++ b/server/tests/e2e/journey.e2e.test.ts @@ -6,10 +6,12 @@ * codes and the unguarded public route. */ import { AddonsService } from '../../src/nest/addons/addons.service'; +import { notFound } from '../../src/nest/common/domain-error'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; import { JourneyBookService } from '../../src/nest/journey/journey-book.service'; import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service'; +import { JourneyMapService } from '../../src/nest/journey/journey-map.service'; import { JourneyShareService } from '../../src/nest/journey/journey-share.service'; import { JourneyModule } from '../../src/nest/journey/journey.module'; import { PhotoCaptureBackfillService } from '../../src/nest/memories/photo-capture-backfill.service'; @@ -110,6 +112,8 @@ const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } })); +const { mapsvc } = vi.hoisted(() => ({ mapsvc: { mapLayers: vi.fn(), publicMapLayers: vi.fn() } })); + const { booksvc } = vi.hoisted(() => ({ booksvc: { getBook: vi.fn(), @@ -134,6 +138,8 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => { .useValue(sharesvc) .overrideProvider(JourneyBookService) .useValue(booksvc) + .overrideProvider(JourneyMapService) + .useValue(mapsvc) .overrideProvider(AddonsService) .useValue({ isAddonEnabled }) .overrideProvider(PhotoCaptureBackfillService) @@ -552,4 +558,62 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => { expect(res.status).toBe(404); expect(res.body).toEqual({ error: 'Not found' }); }); + + // ── Map layers (JRN-04) ─────────────────────────────────────────────────── + + const PLACE = { + place_id: 4, + trip_id: 2, + trip_title: 'Venice', + name: 'Piazza San Marco', + lat: 45.434, + lng: 12.3388, + days: ['2026-05-14'], + time: null, + category_color: null, + category_icon: null, + entry_id: 7, + }; + + it('401 for the map layers without a session', async () => { + expect((await request(server).get('/api/journeys/9/map-layers')).status).toBe(401); + }); + + it('200 with each source on its own, a failed one beside the others', async () => { + mapsvc.mapLayers.mockResolvedValueOnce({ + places: { status: 'ok', items: [PLACE] }, + routes: { status: 'unavailable' }, + stays: { status: 'ok', items: [] }, + }); + const res = await request(server).get('/api/journeys/9/map-layers').set('Cookie', sessionCookie(1)); + expect(res.status).toBe(200); + expect(res.body.places.items).toEqual([PLACE]); + expect(res.body.routes).toEqual({ status: 'unavailable' }); + expect(mapsvc.mapLayers).toHaveBeenCalledWith(9, 1); + }); + + it('404 for the map layers of a journey out of reach', async () => { + mapsvc.mapLayers.mockRejectedValueOnce(notFound('Journey not found')); + const res = await request(server).get('/api/journeys/9/map-layers').set('Cookie', sessionCookie(1)); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Journey not found' }); + }); + + it('public map layers are unguarded and answer what the link shares, 404 for an unknown token', async () => { + mapsvc.publicMapLayers.mockResolvedValueOnce({ + places: { status: 'withheld' }, + routes: { status: 'withheld' }, + stays: { status: 'ok', items: [] }, + recordings: { status: 'withheld' }, + }); + const res = await request(server).get('/api/public/journey/tok/map-layers'); + expect(res.status).toBe(200); + expect(res.body.places).toEqual({ status: 'withheld' }); + expect(mapsvc.publicMapLayers).toHaveBeenCalledWith('tok'); + + mapsvc.publicMapLayers.mockResolvedValueOnce(null); + const missing = await request(server).get('/api/public/journey/bad/map-layers'); + expect(missing.status).toBe(404); + expect(missing.body).toEqual({ error: 'Not found' }); + }); }); diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index d233d5a9a..c3abc4bee 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -85,6 +85,7 @@ const UNNUMBERED = [ 'Migration20200101046160_a_journey_keeps_its_recorded_days', 'Migration20200101046170_a_journey_entry_remembers_the_stays_it_came_from', 'Migration20200101046180_journeys_can_prepare_recorded_days', + 'Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/repositories/JourneyEntryStays.repository.test.ts b/server/tests/unit/db/repositories/JourneyEntryStays.repository.test.ts index 4a7c26258..2306a7d39 100644 --- a/server/tests/unit/db/repositories/JourneyEntryStays.repository.test.ts +++ b/server/tests/unit/db/repositories/JourneyEntryStays.repository.test.ts @@ -137,4 +137,39 @@ describe('JourneyEntryStaysRepository', () => { await deleteRows(t, JourneyEntries, { id: second }); expect(await countRows(t, JourneyEntryStays, {})).toBe(1); }); + + it('JESTAYS-005: the map reads the located stays of a journey by entry, in the order they were lived', async () => { + const { user, journey, entryId } = await journeyWithEntry(); + const second = await entry(journey.id, user.id, 'Afternoon'); + const other = await makeJourney(t, user.id); + await stays.insertStays([ + stay(journey.id, second, user.id, { source_visit_id: '300', name: 'Giudecca' }), + stay(journey.id, entryId, user.id, { source_visit_id: '102', name: 'Rialto', sort_order: 1 }), + stay(journey.id, entryId, user.id, { source_visit_id: '101', name: 'San Marco', sort_order: 0 }), + stay(journey.id, entryId, user.id, { + source_visit_id: '103', + name: 'Nowhere', + lat: null, + lng: null, + sort_order: 2, + }), + ]); + await stays.insertStays([stay(other.id, entryId, user.id, { source_visit_id: '400' })]); + + const located = await stays.listLocatedForJourney(journey.id); + expect(located.map((s) => [s.entry_id, s.name])).toEqual([ + [entryId, 'San Marco'], + [entryId, 'Rialto'], + [second, 'Giudecca'], + ]); + expect(located[0]).toEqual({ + id: expect.any(Number), + entry_id: entryId, + name: 'San Marco', + lat: 45.434, + lng: 12.3388, + started_at: '2026-05-14T09:10:00+02:00', + ended_at: '2026-05-14T10:05:00+02:00', + }); + }); }); diff --git a/server/tests/unit/db/repositories/JourneyTripsMap.repository.test.ts b/server/tests/unit/db/repositories/JourneyTripsMap.repository.test.ts new file mode 100644 index 000000000..1f571b756 --- /dev/null +++ b/server/tests/unit/db/repositories/JourneyTripsMap.repository.test.ts @@ -0,0 +1,105 @@ +/** + * `JourneyTripsRepository`'s journey map reads (JRN-04): the located places + * the linked trips plan on a day, one row per day, and the places of those + * trips that carry a route, both through `journey_trips` so a trip nobody + * has written about counts too. + */ +import { JourneyTrips } from '../../../../src/db/entities/JourneyTrips.entity'; +import type { JourneyTripsRepository } from '../../../../src/db/repositories/JourneyTrips.repository'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeDayAssignment } from '../../../helpers/factories/itinerary'; +import { linkTripToJourney, makeJourney } from '../../../helpers/factories/journeys'; +import { makeCategory, makePlace } from '../../../helpers/factories/places'; +import { makeTrip, readTripDays } from '../../../helpers/factories/trips'; +import { makeUser } from '../../../helpers/factories/users'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let repo: JourneyTripsRepository; + +beforeAll(async () => { + t = await createTestOrm(testDb); + repo = t.repo(JourneyTrips); +}); +beforeEach(() => { + resetTestDb(testDb); + t.clear(); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +async function linkedTrip() { + const { user } = await makeUser(t); + const journey = await makeJourney(t, user.id); + const trip = await makeTrip(t, user.id, { title: 'Venice', start_date: '2026-05-14', end_date: '2026-05-15' }); + await linkTripToJourney(t, journey.id, trip.id); + const [first, second] = await readTripDays(t, trip.id); + if (!first || !second) throw new Error('the trip has no two days'); + return { user, journey, trip, first, second }; +} + +describe('JourneyTripsRepository map reads', () => { + it('JTRIPMAP-001: one row per planned day of a located place, the assignment time before the place time', async () => { + const { user, journey, trip, first, second } = await linkedTrip(); + const category = await makeCategory(t, { color: '#e11d48', icon: 'landmark' }); + const square = await makePlace(t, trip.id, { name: 'San Marco', lat: 45.434, lng: 12.3388, category: category.id }); + const bridge = await makePlace(t, trip.id, { + name: 'Rialto', + lat: 45.438, + lng: 12.336, + place_time: '16:00', + category: null, + }); + const nowhere = await makePlace(t, trip.id, { name: 'Nowhere', lat: null, lng: null }); + await makePlace(t, trip.id, { name: 'Wishlist', lat: 45.43, lng: 12.33 }); + await makeDayAssignment(t, first.id, square.id, { assignment_time: '10:00' }); + await makeDayAssignment(t, second.id, bridge.id); + await makeDayAssignment(t, second.id, square.id); + await makeDayAssignment(t, first.id, nowhere.id); + const unlinked = await makeTrip(t, user.id, { start_date: '2026-05-14', end_date: '2026-05-14' }); + const [unlinkedDay] = await readTripDays(t, unlinked.id); + if (!unlinkedDay) throw new Error('the trip has no day'); + await makeDayAssignment(t, unlinkedDay.id, (await makePlace(t, unlinked.id, { name: 'Elsewhere' })).id); + + const rows = await repo.listMapPlacesForJourney(journey.id); + + expect(rows).toEqual([ + { + place_id: square.id, + trip_id: trip.id, + trip_title: 'Venice', + name: 'San Marco', + lat: 45.434, + lng: 12.3388, + day_date: '2026-05-14', + time: '10:00', + category_color: '#e11d48', + category_icon: 'landmark', + }, + expect.objectContaining({ place_id: bridge.id, day_date: '2026-05-15', time: '16:00', category_color: null }), + expect.objectContaining({ place_id: square.id, day_date: '2026-05-15', time: null }), + ]); + }); + + it('JTRIPMAP-002: the routes of the linked trips, with or without an entry, and nothing of other trips', async () => { + const { user, journey, trip } = await linkedTrip(); + const route = JSON.stringify([ + [45.43, 12.33], + [45.44, 12.34], + ]); + const ridge = await makePlace(t, trip.id, { name: 'Ridge', route_geometry: route, route_color: '#aa0000' }); + await makePlace(t, trip.id, { name: 'No route' }); + const other = await makeTrip(t, user.id); + await makePlace(t, other.id, { name: 'Other', route_geometry: route }); + + expect(await repo.listRouteSourcesForJourney(journey.id)).toEqual([ + { place_id: ridge.id, trip_id: trip.id, name: 'Ridge', route_color: '#aa0000', route_geometry: route }, + ]); + }); +}); diff --git a/server/tests/unit/nest/journey-map.controller.test.ts b/server/tests/unit/nest/journey-map.controller.test.ts new file mode 100644 index 000000000..cbce41978 --- /dev/null +++ b/server/tests/unit/nest/journey-map.controller.test.ts @@ -0,0 +1,40 @@ +/** + * JourneyMapController (JRN-04): the journey map's layers route, its guards, + * its contract and what it hands 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 { JourneyMapController } from '../../../src/nest/journey/journey-map.controller'; +import type { JourneyMapService } from '../../../src/nest/journey/journey-map.service'; +import type { User } from '../../../src/types'; +import { RequestMethod } from '@nestjs/common'; +import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants'; + +import { describe, expect, it, vi } from 'vitest'; + +describe('JourneyMapController', () => { + it('JRNMAP-CTL-001: GET :id/map-layers behind the Journey addon before auth', () => { + expect(Reflect.getMetadata(PATH_METADATA, JourneyMapController)).toBe('api/journeys'); + expect(Reflect.getMetadata(GUARDS_METADATA, JourneyMapController)).toEqual([AddonGuard, JwtAuthGuard]); + expect(Reflect.getMetadata(REQUIRE_ADDON, JourneyMapController)).toEqual({ addonId: 'journey', label: 'Journey' }); + const handler = JourneyMapController.prototype.layers; + expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.GET); + expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe(':id/map-layers'); + }); + + it('JRNMAP-CTL-002: hands the journey and the caller to the service and answers what it read', async () => { + const layers = { + places: { status: 'ok', items: [] }, + routes: { status: 'unavailable' }, + stays: { status: 'ok', items: [] }, + }; + const mapLayers = vi.fn(async () => layers); + const controller = new JourneyMapController({ mapLayers } as unknown as JourneyMapService); + + expect(await controller.layers({ id: 4 } as User, '9')).toBe(layers); + expect(mapLayers).toHaveBeenCalledWith(9, 4); + }); +}); diff --git a/server/tests/unit/nest/journey-map.mcp.test.ts b/server/tests/unit/nest/journey-map.mcp.test.ts new file mode 100644 index 000000000..7372d76aa --- /dev/null +++ b/server/tests/unit/nest/journey-map.mcp.test.ts @@ -0,0 +1,106 @@ +/** + * JourneyMapMcp (JRN-04): the journey map's layers over MCP, on the same + * service and journey access as REST. Places and stays come with their + * positions; a route answers with its name and size, never its geometry. + */ +import { Places } from '../../../src/db/entities/Places.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 { JourneyMapMcp } from '../../../src/nest/journey/journey-map.mcp'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { makeDayAssignment } from '../../helpers/factories/itinerary'; +import { linkTripToJourney, makeJourney } from '../../helpers/factories/journeys'; +import { makePlace } from '../../helpers/factories/places'; +import { updateRows } from '../../helpers/factories/rows'; +import { makeTrip, readTripDays } from '../../helpers/factories/trips'; +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 { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let mcp: JourneyMapMcp; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [JourneyDomainModule, AddonsModule], providers: [JourneyMapMcp] }); + mcp = t.get(JourneyMapMcp); + orm = await createTestOrm(db); +}); +beforeEach(() => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); +}); +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); +} + +describe('JourneyMapMcp', () => { + it('JRNMAP-MCP-001: answers the plan with its positions and a route by its size, without geometry', async () => { + const { user } = await makeUser(orm); + const journey = await makeJourney(orm, user.id, { show_trip_tracks: 1 }); + const trip = await makeTrip(orm, user.id, { start_date: '2026-05-14', end_date: '2026-05-14' }); + await linkTripToJourney(orm, journey.id, trip.id); + const [day] = await readTripDays(orm, trip.id); + if (!day) throw new Error('the trip has no day'); + const square = await makePlace(orm, trip.id, { name: 'San Marco', lat: 45.434, lng: 12.3388 }); + await makeDayAssignment(orm, day.id, square.id); + await updateRows( + orm, + Places, + { id: square.id }, + { + route_geometry: JSON.stringify([ + [45.43, 12.33], + [45.44, 12.34], + [45.45, 12.35], + ]), + }, + ); + + const answer = read(await mcp.getJourneyMapLayers({ journeyId: journey.id }, ctx(user.id))); + + expect(answer.places.items).toEqual([ + expect.objectContaining({ name: 'San Marco', lat: 45.434, lng: 12.3388, days: ['2026-05-14'], entry_id: null }), + ]); + expect(answer.routes).toEqual({ + status: 'ok', + items: [{ place_id: square.id, trip_id: trip.id, name: 'San Marco', points: 3 }], + }); + expect(answer.stays).toEqual({ status: 'ok', items: [] }); + }); + + it('JRNMAP-MCP-002: a stranger is refused like REST, and the tool reads under the Journey addon', async () => { + const { user: owner } = await makeUser(orm); + const { user: stranger } = await makeUser(orm); + const journey = await makeJourney(orm, owner.id); + + await expect(mcp.getJourneyMapLayers({ journeyId: journey.id }, ctx(stranger.id))).rejects.toThrow( + 'Journey not found', + ); + + const entry = getEntry(JourneyMapMcp as unknown as ClassRef, 'getJourneyMapLayers'); + if (entry?.kind !== 'tool') throw new Error('getJourneyMapLayers is no tool'); + expect(entry.options.access).toEqual({ group: 'journey', mode: 'read' }); + const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false); + expect(await entry.options.when?.(ctx(owner.id), mcp)).toBe(false); + enabled.mockResolvedValue(true); + expect(await entry.options.when?.(ctx(owner.id), mcp)).toBe(true); + }); +}); diff --git a/server/tests/unit/nest/journey-map.service.test.ts b/server/tests/unit/nest/journey-map.service.test.ts new file mode 100644 index 000000000..c9f8e119f --- /dev/null +++ b/server/tests/unit/nest/journey-map.service.test.ts @@ -0,0 +1,341 @@ +/** + * JourneyMapService (JRN-04): what the journey map shows beside its entries + * and photos. The suite takes the service from the journey domain module over + * a snapshot test db, so the access check, the share link and the kept rows + * are the real ones. + * + * What it pins: the plan comes through the linked trips, written about or + * not, one pin per place with every day and the entry written about it; a + * position that is not one is left out, never moved; one source failing + * leaves the others; a stranger reads nothing; the share link cuts every + * source on the server by its flags, keeps drafts out and shows nothing while + * the map is not shared. + */ +import { JourneyTrips } from '../../../src/db/entities/JourneyTrips.entity'; +import { Journeys } from '../../../src/db/entities/Journeys.entity'; +import { Places } from '../../../src/db/entities/Places.entity'; +import { DomainError } from '../../../src/nest/common/domain-error'; +import { JourneyDomainModule } from '../../../src/nest/journey/journey-domain.module'; +import { JourneyEntryStaysService } from '../../../src/nest/journey/journey-entry-stays.service'; +import { JourneyMapService } from '../../../src/nest/journey/journey-map.service'; +import { JourneyRecordedDaysService } from '../../../src/nest/journey/journey-recorded-days.service'; +import { JourneyShareService } from '../../../src/nest/journey/journey-share.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { makeDayAssignment } from '../../helpers/factories/itinerary'; +import { + addJourneyContributor, + linkTripToJourney, + makeJourney, + makeJourneyEntry, +} from '../../helpers/factories/journeys'; +import { makeCategory, makePlace } from '../../helpers/factories/places'; +import { updateRows } from '../../helpers/factories/rows'; +import { makeTrip, readTripDays } from '../../helpers/factories/trips'; +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 { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let map: JourneyMapService; +let share: JourneyShareService; +let stays: JourneyEntryStaysService; +let recorded: JourneyRecordedDaysService; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [JourneyDomainModule] }); + map = t.get(JourneyMapService); + share = t.get(JourneyShareService); + stays = t.get(JourneyEntryStaysService); + recorded = t.get(JourneyRecordedDaysService); + orm = await createTestOrm(db); +}); +beforeEach(() => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const ROUTE = JSON.stringify([ + [45.43, 12.33], + [45.44, 12.34], +]); + +/** A journey with one linked trip of two days, nobody having written about it yet. */ +async function venice() { + const { user } = await makeUser(orm, { username: 'marta' }); + const journey = await makeJourney(orm, user.id, { show_trip_tracks: 1 }); + const trip = await makeTrip(orm, user.id, { title: 'Venice', start_date: '2026-05-14', end_date: '2026-05-15' }); + await linkTripToJourney(orm, journey.id, trip.id); + const [first, second] = await readTripDays(orm, trip.id); + const category = await makeCategory(orm, { color: '#e11d48', icon: 'landmark' }); + const square = await makePlace(orm, trip.id, { + name: 'Piazza San Marco', + lat: 45.434, + lng: 12.3388, + category: category.id, + }); + const bridge = await makePlace(orm, trip.id, { name: 'Rialto', lat: 45.438, lng: 12.336, place_time: '16:00' }); + if (!first || !second) throw new Error('the trip has no two days'); + await makeDayAssignment(orm, first.id, square.id, { assignment_time: '10:00' }); + await makeDayAssignment(orm, second.id, square.id); + await makeDayAssignment(orm, second.id, bridge.id); + return { user, journey, trip, square, bridge, days: [first, second] }; +} + +const keep = (journeyId: number, userId: number, date: string) => + recorded.keep( + journeyId, + userId, + { + date, + sourceKind: 'tracks', + utcOffsetMinutes: 120, + window: { from: `${date}T00:00:00+02:00`, to: `${date}T23:59:59+02:00` }, + segments: [ + { + points: [ + [45.434, 12.3388], + [45.4364, 12.3218], + ], + mode: 'walking', + startedAt: `${date}T09:00:00+02:00`, + endedAt: `${date}T09:40:00+02:00`, + distanceMeters: 1500, + }, + ], + truncated: false, + fetchedAt: `${date}T23:59:59+02:00`, + contentHash: 'a'.repeat(64), + }, + false, + ); + +const stayAt = (sourceVisitId: string, lat: number | null, lng: number | null) => ({ + sourceVisitId, + name: `Stay ${sourceVisitId}`, + lat, + lng, + startedAt: '2026-05-14T09:00:00+02:00', + endedAt: '2026-05-14T10:00:00+02:00', + durationMinutes: 60, +}); + +describe('JourneyMapService.mapLayers', () => { + it('JRNMAP-001: a linked trip nobody wrote about shows its plan, one pin per place with every day it stands on', async () => { + const { user, journey, trip, square, bridge } = await venice(); + + const layers = await map.mapLayers(journey.id, user.id); + + expect(layers.places).toEqual({ + status: 'ok', + items: [ + { + place_id: square.id, + trip_id: trip.id, + trip_title: 'Venice', + name: 'Piazza San Marco', + lat: 45.434, + lng: 12.3388, + days: ['2026-05-14', '2026-05-15'], + time: '10:00', + category_color: '#e11d48', + category_icon: 'landmark', + entry_id: null, + }, + expect.objectContaining({ place_id: bridge.id, days: ['2026-05-15'], time: '16:00', entry_id: null }), + ], + }); + expect(layers.stays).toEqual({ status: 'ok', items: [] }); + }); + + it('JRNMAP-002: a place points at the earliest entry written about it; the mirrored skeleton is no entry', async () => { + const { user, journey, square } = await venice(); + await makeJourneyEntry(orm, journey.id, user.id, { + type: 'skeleton', + sourcePlace: square.id, + entry_date: '2026-05-13', + }); + await makeJourneyEntry(orm, journey.id, user.id, { sourcePlace: square.id, entry_date: '2026-05-15' }); + const earlier = await makeJourneyEntry(orm, journey.id, user.id, { + sourcePlace: square.id, + entry_date: '2026-05-14', + }); + + const layers = await map.mapLayers(journey.id, user.id); + + expect(layers.places.status === 'ok' && layers.places.items.find((p) => p.place_id === square.id)?.entry_id).toBe( + earlier.id, + ); + }); + + it('JRNMAP-003: a place without coordinates or with ones off the globe is left out, never put somewhere', async () => { + const { user, journey, trip, days } = await venice(); + const nowhere = await makePlace(orm, trip.id, { name: 'Nowhere', lat: null, lng: null }); + const offGlobe = await makePlace(orm, trip.id, { name: 'Off', lat: 120, lng: 12 }); + await makeDayAssignment(orm, days[0].id, nowhere.id); + await makeDayAssignment(orm, days[0].id, offGlobe.id); + + const layers = await map.mapLayers(journey.id, user.id); + + const names = layers.places.status === 'ok' ? layers.places.items.map((p) => p.name) : []; + expect(names).toEqual(['Piazza San Marco', 'Rialto']); + }); + + it('JRNMAP-004: the routes come through the linked trips while the track switch is on, broken geometry left out', async () => { + const { user, journey, trip, square, bridge } = await venice(); + await updateRows(orm, Places, { id: square.id }, { route_geometry: ROUTE, route_color: '#123456' }); + await updateRows(orm, Places, { id: bridge.id }, { route_geometry: 'not json' }); + + const on = await map.mapLayers(journey.id, user.id); + expect(on.routes).toEqual({ + status: 'ok', + items: [ + { + place_id: square.id, + trip_id: trip.id, + name: 'Piazza San Marco', + color: '#123456', + points: [ + [45.43, 12.33], + [45.44, 12.34], + ], + kind: 'trip_gpx', + }, + ], + }); + + await updateRows(orm, Journeys, { id: journey.id }, { show_trip_tracks: 0 }); + expect((await map.mapLayers(journey.id, user.id)).routes).toEqual({ status: 'ok', items: [] }); + }); + + it('JRNMAP-005: the located stays of an entry each come with their own place; one without a place stays off', async () => { + const { user, journey } = await venice(); + const report = await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-14', title: 'Day report' }); + await stays.record(journey.id, report.id, user.id, [ + stayAt('1', 45.434, 12.3388), + stayAt('2', null, null), + stayAt('3', 45.438, 12.336), + ]); + + const layers = await map.mapLayers(journey.id, user.id); + + expect(layers.stays.status === 'ok' && layers.stays.items.map((s) => [s.entry_id, s.name, s.lat])).toEqual([ + [report.id, 'Stay 1', 45.434], + [report.id, 'Stay 3', 45.438], + ]); + }); + + it('JRNMAP-006: one source failing answers unavailable and the others still draw', async () => { + const { user, journey } = await venice(); + const trips = orm.repo(JourneyTrips); + vi.spyOn(Object.getPrototypeOf(trips), 'listMapPlacesForJourney').mockRejectedValueOnce(new Error('disk')); + + const layers = await map.mapLayers(journey.id, user.id); + + expect(layers.places).toEqual({ status: 'unavailable' }); + expect(layers.routes.status).toBe('ok'); + expect(layers.stays.status).toBe('ok'); + }); + + it('JRNMAP-007: a contributor reads the layers, a stranger gets the journey 404', async () => { + const { journey } = await venice(); + const { user: viewer } = await makeUser(orm); + const { user: stranger } = await makeUser(orm); + await addJourneyContributor(orm, journey.id, viewer.id, 'viewer'); + + expect((await map.mapLayers(journey.id, viewer.id)).places.status).toBe('ok'); + await expect(map.mapLayers(journey.id, stranger.id)).rejects.toBeInstanceOf(DomainError); + }); +}); + +describe('JourneyMapService.publicMapLayers', () => { + async function shared(flags: Parameters[2]) { + const scene = await venice(); + const link = await share.createOrUpdateJourneyShareLink(scene.journey.id, scene.user.id, flags); + if (!link) throw new Error('the owner could not share'); + return { ...scene, token: link.token }; + } + + it('JRNMAP-008: an unknown token answers null', async () => { + expect(await map.publicMapLayers('nope')).toBeNull(); + }); + + it('JRNMAP-009: with the map not shared nothing is, whatever the other flags say', async () => { + const { token } = await shared({ share_map: false, share_plan: true, share_recordings: true }); + expect(await map.publicMapLayers(token)).toEqual({ + places: { status: 'withheld' }, + routes: { status: 'withheld' }, + stays: { status: 'withheld' }, + recordings: { status: 'withheld' }, + }); + }); + + it('JRNMAP-010: a new link shares neither the plan nor the recorded days; stays of published entries do show', async () => { + const { token, journey, user } = await shared({}); + const published = await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-14' }); + const draft = await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-14', is_draft: 1 }); + await stays.record(journey.id, published.id, user.id, [stayAt('1', 45.434, 12.3388)]); + await stays.record(journey.id, draft.id, user.id, [stayAt('2', 45.438, 12.336)]); + await keep(journey.id, user.id, '2026-05-14'); + + const layers = await map.publicMapLayers(token); + + expect(layers?.places).toEqual({ status: 'withheld' }); + expect(layers?.routes).toEqual({ status: 'withheld' }); + expect(layers?.recordings).toEqual({ status: 'withheld' }); + expect(layers?.stays.status === 'ok' && layers.stays.items.map((s) => s.entry_id)).toEqual([published.id]); + }); + + it('JRNMAP-011: the plan shows with share_plan, tied only to published entries; routes also need the track switch', async () => { + const { token, journey, user, square } = await shared({ share_plan: true }); + await makeJourneyEntry(orm, journey.id, user.id, { sourcePlace: square.id, entry_date: '2026-05-14', is_draft: 1 }); + await updateRows(orm, Places, { id: square.id }, { route_geometry: ROUTE }); + + const layers = await map.publicMapLayers(token); + + expect(layers?.places.status === 'ok' && layers.places.items.map((p) => [p.name, p.entry_id])).toEqual([ + ['Piazza San Marco', null], + ['Rialto', null], + ]); + expect(layers?.routes.status === 'ok' && layers.routes.items).toHaveLength(1); + + await updateRows(orm, Journeys, { id: journey.id }, { show_trip_tracks: 0 }); + expect((await map.publicMapLayers(token))?.routes).toEqual({ status: 'withheld' }); + }); + + it('JRNMAP-012: a recorded day shows with share_recordings only beside a published entry of that day', async () => { + const { token, journey, user } = await shared({ share_recordings: true }); + await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-14' }); + await makeJourneyEntry(orm, journey.id, user.id, { entry_date: '2026-05-15', is_draft: 1 }); + await keep(journey.id, user.id, '2026-05-14'); + await keep(journey.id, user.id, '2026-05-15'); + + const layers = await map.publicMapLayers(token); + + expect(layers?.recordings).toEqual({ + status: 'ok', + items: [ + { + date: '2026-05-14', + pieces: [ + [ + [45.434, 12.3388], + [45.4364, 12.3218], + ], + ], + distance_m: expect.any(Number), + }, + ], + }); + }); +}); diff --git a/server/tests/unit/nest/journey-share.service.test.ts b/server/tests/unit/nest/journey-share.service.test.ts index d8e4a2b8b..707961be5 100644 --- a/server/tests/unit/nest/journey-share.service.test.ts +++ b/server/tests/unit/nest/journey-share.service.test.ts @@ -292,6 +292,27 @@ describe('createOrUpdateJourneyShareLink', () => { expect((await svc.getJourneyShareLink(journey.id))!.newest_first).toBe(true); }); + it('JOURNEY-SHARE-030: the plan and the recorded days start unshared, are set apart and survive other updates (JRN-04)', async () => { + const { user } = createUser(testDb); + const journey = createJourney(testDb, user.id); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, {}); + let link = await svc.getJourneyShareLink(journey.id); + expect(link!.share_plan).toBe(false); + expect(link!.share_recordings).toBe(false); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_plan: true }); + link = await svc.getJourneyShareLink(journey.id); + expect(link!.share_plan).toBe(true); + expect(link!.share_recordings).toBe(false); + + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_recordings: true, share_gallery: false }); + await svc.createOrUpdateJourneyShareLink(journey.id, user.id, { share_timeline: false }); + link = await svc.getJourneyShareLink(journey.id); + expect(link!.share_plan).toBe(true); + expect(link!.share_recordings).toBe(true); + }); + it('JOURNEY-SHARE-004: different journeys get different tokens', async () => { const { user } = createUser(testDb); const j1 = createJourney(testDb, user.id); diff --git a/server/tests/unit/nest/journey.controller.test.ts b/server/tests/unit/nest/journey.controller.test.ts index f92c45f73..17d2ee004 100644 --- a/server/tests/unit/nest/journey.controller.test.ts +++ b/server/tests/unit/nest/journey.controller.test.ts @@ -1088,6 +1088,25 @@ describe('JourneyPublicController', () => { ).toEqual({ id: 1 }); }); + it('GET /:token/map-layers 404 on an unknown link, else the layers as the service cut them (JRN-04)', async () => { + expect( + await thrownAsync(() => + new JourneyPublicController( + svc({ getPublicMapLayers: vi.fn().mockResolvedValue(null) } as Partial), + storageStub, + ).mapLayers('tok'), + ), + ).toEqual({ status: 404, body: { error: 'Not found' } }); + const layers = { places: { status: 'withheld' } }; + const getPublicMapLayers = vi.fn().mockResolvedValue(layers); + expect( + await new JourneyPublicController(svc({ getPublicMapLayers } as Partial), storageStub).mapLayers( + 'tok', + ), + ).toBe(layers); + expect(getPublicMapLayers).toHaveBeenCalledWith('tok'); + }); + it('photo proxy 404 on invalid token, else streams', async () => { expect( await thrownAsync(() => diff --git a/shared/src/index.ts b/shared/src/index.ts index d08dda99f..98fb8e26e 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -103,6 +103,7 @@ export * from './journey/journey.schema'; export * from './journey/journey-recordings.schema'; export * from './journey/journey-day-import.schema'; export * from './journey/journey-recording-prep.schema'; +export * from './journey/journey-map.schema'; export * from './journey/trip-journal-link.schema'; export * from './book/book.schema'; export * from './book/journey-stats.schema'; diff --git a/shared/src/journey/journey-map.schema.spec.ts b/shared/src/journey/journey-map.schema.spec.ts new file mode 100644 index 000000000..7bfa90755 --- /dev/null +++ b/shared/src/journey/journey-map.schema.spec.ts @@ -0,0 +1,78 @@ +import { journeyMapLayersResponseSchema, journeyPublicMapLayersResponseSchema } from './journey-map.schema'; + +import { describe, expect, it } from 'vitest'; + +const place = { + place_id: 4, + trip_id: 2, + trip_title: 'Venice', + name: 'Piazza San Marco', + lat: 45.434, + lng: 12.3388, + days: ['2026-05-14'], + time: '10:00', + category_color: '#e11d48', + category_icon: 'landmark', + entry_id: null, +}; + +describe('journeyMapLayersResponseSchema', () => { + it('JRNMAP-SCHEMA-001: each source answers on its own, a failed one beside the others', () => { + const parsed = journeyMapLayersResponseSchema.safeParse({ + places: { status: 'ok', items: [place] }, + routes: { status: 'unavailable' }, + stays: { status: 'ok', items: [] }, + }); + expect(parsed.success).toBe(true); + }); + + it('JRNMAP-SCHEMA-002: refuses a status it does not know and items on a source that has none', () => { + expect( + journeyMapLayersResponseSchema.safeParse({ + places: { status: 'partial', items: [] }, + routes: { status: 'ok', items: [] }, + stays: { status: 'ok', items: [] }, + }).success, + ).toBe(false); + expect( + journeyMapLayersResponseSchema.safeParse({ + places: { status: 'ok', items: [{ ...place, lat: 'north' }] }, + routes: { status: 'ok', items: [] }, + stays: { status: 'ok', items: [] }, + }).success, + ).toBe(false); + }); +}); + +describe('journeyPublicMapLayersResponseSchema', () => { + it('JRNMAP-SCHEMA-003: the public answer carries the recorded days, a withheld source as such', () => { + const parsed = journeyPublicMapLayersResponseSchema.safeParse({ + places: { status: 'withheld' }, + routes: { status: 'withheld' }, + stays: { status: 'ok', items: [] }, + recordings: { + status: 'ok', + items: [ + { + date: '2026-05-14', + pieces: [ + [ + [45.43, 12.33], + [45.44, 12.34], + ], + ], + distance_m: 1520, + }, + ], + }, + }); + expect(parsed.success).toBe(true); + expect( + journeyPublicMapLayersResponseSchema.safeParse({ + places: { status: 'withheld' }, + routes: { status: 'withheld' }, + stays: { status: 'withheld' }, + }).success, + ).toBe(false); + }); +}); diff --git a/shared/src/journey/journey-map.schema.ts b/shared/src/journey/journey-map.schema.ts new file mode 100644 index 000000000..cf611350c --- /dev/null +++ b/shared/src/journey/journey-map.schema.ts @@ -0,0 +1,92 @@ +import { journeyTrackSchema } from './journey.schema'; + +import { z } from 'zod'; + +/** + * JRN-04: what the journey map can show besides the entries and the photos + * the journey answers itself: the plan of its trips, the days of route it + * keeps and the stays its entries were taken over from. + * + * Every source answers on its own. One that failed says `unavailable` and the + * others still draw; one a share link does not show says `withheld`, so a + * reader is never offered a layer that is not theirs to switch on. Nothing + * here stands for a visit: a planned place is what the trip meant to do. + */ + +/** A place of a linked trip on the day(s) the plan puts it on. */ +export const journeyMapPlaceSchema = z.object({ + place_id: z.number(), + trip_id: z.number(), + trip_title: z.string(), + name: z.string(), + lat: z.number(), + lng: z.number(), + /** The days of the plan it is on, `YYYY-MM-DD`, earliest first. */ + days: z.array(z.string()), + /** The time the plan gives it on its first day, `HH:MM`, or null. */ + time: z.string().nullable(), + category_color: z.string().nullable(), + category_icon: z.string().nullable(), + /** The journal entry written about it, when there is one; a planned place is no visit by itself. */ + entry_id: z.number().nullable(), +}); +export type JourneyMapPlace = z.infer; + +/** One stay a journal entry was taken over from (JRN-02), at the place it was recorded. */ +export const journeyMapStaySchema = z.object({ + id: z.number(), + entry_id: z.number(), + name: z.string(), + lat: z.number(), + lng: z.number(), + started_at: z.string(), + ended_at: z.string(), +}); +export type JourneyMapStay = z.infer; + +/** A day of route the journey keeps (JRN-01), its pieces apart: a gap stays a gap. */ +export const journeyMapRecordingSchema = z.object({ + date: z.string(), + pieces: z.array(z.array(z.tuple([z.number(), z.number()]))), + distance_m: z.number().nullable(), +}); +export type JourneyMapRecording = z.infer; + +/** How one source of the map answered. */ +function layerResult(item: T) { + return z.discriminatedUnion('status', [ + z.object({ status: z.literal('ok'), items: z.array(item) }), + z.object({ status: z.literal('unavailable') }), + z.object({ status: z.literal('withheld') }), + ]); +} + +export const journeyMapPlacesLayerSchema = layerResult(journeyMapPlaceSchema); +export const journeyMapRoutesLayerSchema = layerResult(journeyTrackSchema); +export const journeyMapStaysLayerSchema = layerResult(journeyMapStaySchema); +export const journeyMapRecordingsLayerSchema = layerResult(journeyMapRecordingSchema); +export type JourneyMapLayerResult = + { status: 'ok'; items: T[] } | { status: 'unavailable' } | { status: 'withheld' }; + +/** + * GET /api/journeys/:id/map-layers. The trips' GPX tracks are the plan's + * routes, drawn while the journey's track switch is on. The recorded days are + * not here: the journey answers them with their details at `/recordings`. + */ +export const journeyMapLayersResponseSchema = z.object({ + places: journeyMapPlacesLayerSchema, + routes: journeyMapRoutesLayerSchema, + stays: journeyMapStaysLayerSchema, +}); +export type JourneyMapLayersResponse = z.infer; + +/** + * GET /api/public/journey/:token/map-layers: the same, cut to what the link + * shares. Nothing while the map is not shared; the plan and its routes only + * with `share_plan`; the recorded days only with `share_recordings` and only + * on a day with a published entry; stays only of published entries. + */ +export const journeyPublicMapLayersResponseSchema = journeyMapLayersResponseSchema.extend({ + recordings: journeyMapRecordingsLayerSchema, +}); +export type JourneyPublicMapLayersResponse = z.infer; diff --git a/shared/src/journey/journey.schema.spec.ts b/shared/src/journey/journey.schema.spec.ts index 4fd7e9514..8edfb787e 100644 --- a/shared/src/journey/journey.schema.spec.ts +++ b/shared/src/journey/journey.schema.spec.ts @@ -87,6 +87,12 @@ describe('journeyShareLinkRequestSchema', () => { // The controller coerces with !!; a string flag has always worked. expect(journeyShareLinkRequestSchema.safeParse({ share_map: 'true' }).success).toBe(true); }); + + it('takes the plan and recordings flags as booleans only, being new (JRN-04)', () => { + expect(journeyShareLinkRequestSchema.safeParse({ share_plan: true, share_recordings: false }).success).toBe(true); + expect(journeyShareLinkRequestSchema.safeParse({ share_plan: 'true' }).success).toBe(false); + expect(journeyShareLinkRequestSchema.safeParse({ share_recordings: 1 }).success).toBe(false); + }); }); describe('the free-form bodies keep their unknown keys', () => { diff --git a/shared/src/journey/journey.schema.ts b/shared/src/journey/journey.schema.ts index 82c9ef61a..d80a08c9d 100644 --- a/shared/src/journey/journey.schema.ts +++ b/shared/src/journey/journey.schema.ts @@ -173,6 +173,10 @@ export const journeyShareLinkRequestSchema = z.looseObject({ share_map: z.unknown().optional(), /** Show the newest entry first, blog-style, rather than in trip order (#1614). */ newest_first: z.unknown().optional(), + /** Put the linked trips' plan on the shared map (JRN-04). Nothing without `share_map`. */ + share_plan: z.boolean().optional(), + /** Put the recorded days on the shared map, on days with a published entry (JRN-04). */ + share_recordings: z.boolean().optional(), }); export type JourneyShareLinkRequest = z.infer; @@ -252,6 +256,8 @@ export const journeyShareLinkSchema = z.object({ share_gallery: z.boolean(), share_map: z.boolean(), newest_first: z.boolean(), + share_plan: z.boolean(), + share_recordings: z.boolean(), }); export type JourneyShareLink = z.infer; diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md index 0617bbc6d..088194700 100644 --- a/wiki/MCP-Addon-Tools.md +++ b/wiki/MCP-Addon-Tools.md @@ -183,6 +183,7 @@ Requires `journey:read` or `journey:write` scope. |---|---| | `list_journeys` | List all journeys owned or contributed to by the current user. | | `get_journey` | Get a full snapshot of a journey — metadata, entries, contributors, and linked trips. | +| `get_journey_map_layers` | What a journey's map shows beside its entries and photos: the planned places of its linked trips with their days and the entry written about each (a plan is no proof of a visit), the trips' GPX routes by name and size while the track switch is on, and the stays journal entries were taken over from, each where it was recorded. Every source answers on its own, `ok` or `unavailable`. | | `get_journey_stats` | What a journey adds up to: distance travelled in metres, calendar days spanned, countries in visit order, the furthest point reached, and entry, photo and place counts. Entries switched off with `stats_excluded` count towards none of those and are listed under `excluded`. Pass `include_route` for the route itself, up to 400 stops with coordinates. | | `create_journey` | Create a new journey with title, optional subtitle, and an initial list of trip IDs. | | `update_journey` | Update a journey's title, subtitle, cover or status, and whether its entries offer a pros/cons list, a mood and a weather note (`show_verdict`, `show_mood`, `show_weather`). `status_override` sets the shown status by hand (`draft`, `live` or `completed`), `null` goes back to following the trip dates. `photo_location` lets an entry without a place take the position of its first geotagged photo. `auto_prepare_recordings` switches the preparation of its recorded days from Dawarich on or off. Owner only. | @@ -205,7 +206,7 @@ Requires `journey:read` or `journey:write` scope. | `get_journey_suggestions` | Get suggested trips to add to journeys based on recent trip history. | | `list_journey_available_trips` | List all trips available to the current user for linking to a journey. | | `get_journey_share_link` | Get the current public share link for a journey. Requires `journey:share`. | -| `create_journey_share_link` | Create or update the public share link for a journey. Requires `journey:share`. | +| `create_journey_share_link` | Create or update the public share link for a journey. `share_plan` adds the linked trips' planned places and GPX routes to the shared map, `share_recordings` the recorded days that have a published entry; both start off and show nothing while the map is not shared. Requires `journey:share`. | | `delete_journey_share_link` | Revoke the public share link for a journey. Requires `journey:share`. | | `list_journey_recorded_days` | The days of recorded route a journey keeps: zone, distance, pieces, gaps, modes, whether the day was still running, and whose recording it is, without the geometry. Readable without a Dawarich connection. | | `delete_journey_recorded_day` | Drop the recorded route a journey keeps for one day. Entries and texts stay, and Dawarich keeps its own recording. Needs edit access. |