feat(journey): keep the route recorded on a journey day from Dawarich, previewed first, with its gaps

A day header in the journey timeline now carries the Dawarich mark for an
editor whose Dawarich answers (dimmed with the reason while offline). It opens
a dialog that names the journey and the day and reads that one local day from
the caller's own connection: a sketch of the route, distance, first and last
time, pieces, gaps without recording, modes and whether tracks or thinned
points answered. The day is cut in the zone Dawarich records in where its
answer shows one, else in this device's, and a picker cuts it in any other.
Nothing is kept before "Keep route". On a phone the same sheet opens from the
journey's More options for the day of the card shown.

What is kept is the preview that was seen: the save reads the day again and
refuses with recording_changed when its hash moved, and the dialog shows the
new version. The same day taken over twice keeps one version and announces
nothing; a different version is replaced only on "Replace", never touching an
entry or text. A failed read throws before any write, so the kept version
stays. Gaps stay gaps: points are split where silence ends elsewhere, and no
day is joined to the one before. The dialog says how many other people will
see the route; editors may keep their own recording.

Kept days show in the day header (distance, whose recording, since when,
still running) and on the desktop and phone journey maps in the colour of
their day's pins, winning over the live trail of their date, and stay drawn
without Dawarich. A trip's GPX track is now drawn dashed as the plan, recorded
routes solid. Shared links do not show recorded days. Remove route asks first
and works without a connection.

Server: migration 046160 adds journey_recorded_days (one row per journey,
local day and source, segments as JSON, zone, window, fetch time, hash,
importer kept past their account). The journey domain owns the rows through
JourneyRecordedDaysService; the new journey-recordings domain takes a day
over through DawarichTracksService.fetchDay, which reads past the cache, asks
a window wide enough for every zone and refuses with DomainErrors. REST under
/api/journeys/:id/recordings (list, preview, PUT and DELETE /:date) with
@trek/shared contracts, and MCP list_journey_recorded_days,
preview_journey_recorded_day, save_journey_recorded_day and
delete_journey_recorded_day on the same service and access. A new user event
journey:recording:updated keeps every open map current. JourneyTrack gains an
optional kind. All 27 locales carry the strings; the Journey and Dawarich wiki
pages and the MCP tool list say what it does.
This commit is contained in:
Maurice
2026-10-21 15:05:21 +02:00
parent cbca3b2851
commit 65bb2d95eb
99 changed files with 6359 additions and 51 deletions
+1
View File
@@ -45,6 +45,7 @@
"JourneyEntries": "journey",
"JourneyEntryPhotos": "journey",
"JourneyPhotos": "journey",
"JourneyRecordedDays": "journey",
"JourneyShareTokens": "journey",
"JourneyTrips": "journey",
"Journeys": "journey",
@@ -0,0 +1,60 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { JourneyRecordedDaysRepository } from '../repositories/JourneyRecordedDays.repository';
import { DbTimestampType } from '../types';
import { Journeys } from './Journeys.entity';
import { Users } from './Users.entity';
export class JourneyRecordedDays {
[EntityRepositoryType]?: JourneyRecordedDaysRepository;
id!: number & Opt;
journey!: Ref<Journeys>;
journey_id!: number;
local_date!: string;
source: string & Opt = 'dawarich';
source_kind!: string;
utc_offset_minutes!: number;
window_from!: string;
window_to!: string;
segments!: string;
point_count!: number;
distance_m?: number | null;
content_hash!: string;
truncated: number & Opt = 0;
fetched_at!: string;
imported_by?: number | null;
created_at!: string & Opt;
updated_at!: string & Opt;
importedByRef?: Ref<Users> | null;
}
export const JourneyRecordedDaysSchema = defineEntity({
class: JourneyRecordedDays,
repository: () => JourneyRecordedDaysRepository,
uniques: [
{
name: 'idx_journey_recorded_days_day',
properties: ['journey_id', 'local_date', 'source'],
},
],
properties: {
id: p.integer().primary(),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden(),
journey_id: p.integer().persist(false),
local_date: p.text(),
source: p.text().default('dawarich'),
source_kind: p.text(),
utc_offset_minutes: p.integer(),
window_from: p.text(),
window_to: p.text(),
segments: p.text(),
point_count: p.integer(),
distance_m: p.double().nullable(),
content_hash: p.text(),
truncated: p.integer().default(0),
fetched_at: p.text(),
imported_by: p.integer().nullable().persist(false).index('idx_journey_recorded_days_imported_by'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
importedByRef: () => p.manyToOne(Users).ref().joinColumn('imported_by').nullable().hidden().index('idx_journey_recorded_days_imported_by'),
},
});
@@ -4,6 +4,7 @@ import { JourneyBooks } from './JourneyBooks.entity';
import { JourneyContributors } from './JourneyContributors.entity';
import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyPhotos } from './JourneyPhotos.entity';
import { JourneyRecordedDays } from './JourneyRecordedDays.entity';
import { JourneyShareTokens } from './JourneyShareTokens.entity';
import { JourneyTrips } from './JourneyTrips.entity';
import { TripJournalLinks } from './TripJournalLinks.entity';
@@ -31,6 +32,7 @@ export class Journeys {
journey_contributors_collection = new Collection<JourneyContributors>(this);
journey_entries_collection = new Collection<JourneyEntries>(this);
journey_photos_collection = new Collection<JourneyPhotos>(this);
journey_recorded_days_collection = new Collection<JourneyRecordedDays>(this);
journey_share_tokens: Ref<JourneyShareTokens> | null = null;
journey_trips_collection = new Collection<JourneyTrips>(this);
trip_journal_links_collection = new Collection<TripJournalLinks>(this);
@@ -60,6 +62,7 @@ export const JourneysSchema = defineEntity({
journey_contributors_collection: () => p.oneToMany(JourneyContributors).mappedBy('journey').hidden(),
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('journey').hidden(),
journey_photos_collection: () => p.oneToMany(JourneyPhotos).mappedBy('journey').hidden(),
journey_recorded_days_collection: () => p.oneToMany(JourneyRecordedDays).mappedBy('journey').hidden(),
journey_share_tokens: () => p.oneToOne(JourneyShareTokens).ref().mappedBy('journey').hidden(),
journey_trips_collection: () => p.oneToMany(JourneyTrips).mappedBy('journey').hidden(),
trip_journal_links_collection: () => p.oneToMany(TripJournalLinks).mappedBy('journey').hidden(),
+3
View File
@@ -30,6 +30,7 @@ import { InviteTokens } from './InviteTokens.entity';
import { JourneyBooks } from './JourneyBooks.entity';
import { JourneyContributors } from './JourneyContributors.entity';
import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyRecordedDays } from './JourneyRecordedDays.entity';
import { JourneyShareTokens } from './JourneyShareTokens.entity';
import { Journeys } from './Journeys.entity';
import { McpTokens } from './McpTokens.entity';
@@ -158,6 +159,7 @@ export class Users {
journey_books_collection1 = new Collection<JourneyBooks>(this);
journey_contributors_collection = new Collection<JourneyContributors>(this);
journey_entries_collection = new Collection<JourneyEntries>(this);
journey_recorded_days_collection = new Collection<JourneyRecordedDays>(this);
journey_share_tokens_collection = new Collection<JourneyShareTokens>(this);
journeys_collection = new Collection<Journeys>(this);
mcp_tokens_collection = new Collection<McpTokens>(this);
@@ -308,6 +310,7 @@ export const UsersSchema = defineEntity({
journey_books_collection1: () => p.oneToMany(JourneyBooks).mappedBy('createdByRef').hidden(),
journey_contributors_collection: () => p.oneToMany(JourneyContributors).mappedBy('user').hidden(),
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('author').hidden(),
journey_recorded_days_collection: () => p.oneToMany(JourneyRecordedDays).mappedBy('importedByRef').hidden(),
journey_share_tokens_collection: () => p.oneToMany(JourneyShareTokens).mappedBy('createdByRef').hidden(),
journeys_collection: () => p.oneToMany(Journeys).mappedBy('user').hidden(),
mcp_tokens_collection: () => p.oneToMany(McpTokens).mappedBy('user').hidden(),
+2
View File
@@ -45,6 +45,7 @@ import { JourneyContributorsSchema } from './JourneyContributors.entity';
import { JourneyEntriesSchema } from './JourneyEntries.entity';
import { JourneyEntryPhotosSchema } from './JourneyEntryPhotos.entity';
import { JourneyPhotosSchema } from './JourneyPhotos.entity';
import { JourneyRecordedDaysSchema } from './JourneyRecordedDays.entity';
import { JourneyShareTokensSchema } from './JourneyShareTokens.entity';
import { JourneyTripsSchema } from './JourneyTrips.entity';
import { JourneysSchema } from './Journeys.entity';
@@ -196,6 +197,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
JourneyEntriesSchema,
JourneyEntryPhotosSchema,
JourneyPhotosSchema,
JourneyRecordedDaysSchema,
JourneyShareTokensSchema,
JourneyTripsSchema,
JourneysSchema,
+13
View File
@@ -1,6 +1,7 @@
import type { JsonColumn } from '../utils/json-column';
import {
FERRATAS_RESULT_CAP,
dawarichTrackSegmentSchema,
ferrataSchema,
hikingPreferencesSchema,
obstacleSnapshotSchema,
@@ -15,6 +16,7 @@ import {
tourSourceHintChangeSchema,
tourWaypointSchema,
trackMarksSchema,
type DawarichTrackSegment,
type Ferrata,
type GeometryPoint,
type HikingPreferences,
@@ -315,3 +317,14 @@ export const TOUR_SOURCE_HINT_CHANGES: JsonColumn<TourSourceHintChange[]> = {
schema: z.array(tourSourceHintChangeSchema),
fallback: () => [],
};
/**
* JRN-01: the pieces of a day's recorded route a journey keeps, each with its
* mode and times. A broken row reads as none, so a day never draws a line it
* cannot vouch for.
*/
export const JOURNEY_RECORDED_DAY_SEGMENTS: JsonColumn<DawarichTrackSegment[]> = {
column: 'journey_recorded_days.segments',
schema: z.array(dawarichTrackSegmentSchema),
fallback: () => [],
};
@@ -0,0 +1,23 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface JourneyRecordedDaysTable {
id: InsertOptional<number>;
journey_id: number;
local_date: string;
source: InsertOptional<string>;
source_kind: string;
utc_offset_minutes: number;
window_from: string;
window_to: string;
segments: string;
point_count: number;
distance_m: InsertOptional<number | null>;
content_hash: string;
truncated: InsertOptional<number>;
fetched_at: string;
imported_by: InsertOptional<number | null>;
created_at: InsertOptional<string>;
updated_at: InsertOptional<string>;
}
+2
View File
@@ -48,6 +48,7 @@ import type { JourneyContributorsTable } from './JourneyContributors.table';
import type { JourneyEntriesTable } from './JourneyEntries.table';
import type { JourneyEntryPhotosTable } from './JourneyEntryPhotos.table';
import type { JourneyPhotosTable } from './JourneyPhotos.table';
import type { JourneyRecordedDaysTable } from './JourneyRecordedDays.table';
import type { JourneyShareTokensTable } from './JourneyShareTokens.table';
import type { JourneyTripsTable } from './JourneyTrips.table';
import type { JourneysTable } from './Journeys.table';
@@ -205,6 +206,7 @@ export interface DB {
journey_entries: JourneyEntriesTable;
journey_entry_photos: JourneyEntryPhotosTable;
journey_photos: JourneyPhotosTable;
journey_recorded_days: JourneyRecordedDaysTable;
journey_share_tokens: JourneyShareTokensTable;
journey_trips: JourneyTripsTable;
journeys: JourneysTable;
@@ -0,0 +1,48 @@
import { Migration } from '@mikro-orm/migrations';
/**
* JRN-01: a journey keeps the route recorded on one of its days, taken over
* from Dawarich on purpose, so the day stays drawn once the connection is
* gone.
*
* One row per journey, local day and source. `segments` holds the recording
* as it was taken (JSON: the thinned pieces with their mode and times, a gap
* between two pieces kept as a gap), `utc_offset_minutes` the zone the day was
* cut in, `window_from`/`window_to` the instants that day ran from and to,
* `fetched_at` when the source answered and `content_hash` what it answered,
* so taking the same day over again replaces nothing that did not change.
* `imported_by` names whose recording it is; the row outlives that account.
*/
export class Migration20200101046160_a_journey_keeps_its_recorded_days extends Migration {
override name = 'Migration20200101046160_a_journey_keeps_its_recorded_days';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS journey_recorded_days (
id INTEGER PRIMARY KEY,
journey_id INTEGER NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
local_date TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'dawarich',
source_kind TEXT NOT NULL,
utc_offset_minutes INTEGER NOT NULL,
window_from TEXT NOT NULL,
window_to TEXT NOT NULL,
segments TEXT NOT NULL,
point_count INTEGER NOT NULL,
distance_m REAL,
content_hash TEXT NOT NULL,
truncated INTEGER NOT NULL DEFAULT 0,
fetched_at TEXT NOT NULL,
imported_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_journey_recorded_days_day ON journey_recorded_days(journey_id, local_date, source)',
);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_journey_recorded_days_imported_by ON journey_recorded_days(imported_by)',
);
}
}
@@ -0,0 +1,125 @@
import type { JourneyRecordedDays } from '../entities/JourneyRecordedDays.entity';
import type { DB } from '../kysely/db';
import { dbNow } from '../types';
import { TrekRepository } from './_shared/trek-repository';
type RecordedDaysDB = Pick<DB, 'journey_recorded_days' | 'users'>;
/** A day as it is taken over; `segments` is its JSON text. */
export interface JourneyRecordedDayWrite {
journey_id: number;
local_date: string;
source: string;
source_kind: string;
utc_offset_minutes: number;
window_from: string;
window_to: string;
segments: string;
point_count: number;
distance_m: number | null;
content_hash: string;
truncated: number;
fetched_at: string;
imported_by: number | null;
}
/** A kept day as it is read back, with the name of whose recording it is. */
export interface JourneyRecordedDayRow extends JourneyRecordedDayWrite {
id: number;
imported_by_username: string | null;
created_at: string;
updated_at: string;
}
/**
* `journey_recorded_days` (JRN-01): the route recorded on a day of a journey,
* taken over on purpose, one version per journey, local day and source. A
* day goes with its journey; it outlives the account that took it over.
*/
export class JourneyRecordedDaysRepository extends TrekRepository<JourneyRecordedDays> {
private db() {
return this.kysely<RecordedDaysDB>();
}
private selectRows() {
return this.db()
.selectFrom('journey_recorded_days as d')
.leftJoin('users as u', 'u.id', 'd.imported_by')
.select([
'd.id',
'd.journey_id',
'd.local_date',
'd.source',
'd.source_kind',
'd.utc_offset_minutes',
'd.window_from',
'd.window_to',
'd.segments',
'd.point_count',
'd.distance_m',
'd.content_hash',
'd.truncated',
'd.fetched_at',
'd.imported_by',
'u.username as imported_by_username',
'd.created_at',
'd.updated_at',
]);
}
/** The days a journey keeps, earliest first. */
async listForJourney(journeyId: number): Promise<JourneyRecordedDayRow[]> {
return await this.selectRows().where('d.journey_id', '=', journeyId).orderBy('d.local_date', 'asc').execute();
}
/** The version a journey keeps for one day of one source; undefined while it keeps none. */
async findDay(journeyId: number, localDate: string, source: string): Promise<JourneyRecordedDayRow | undefined> {
return await this.selectRows()
.where('d.journey_id', '=', journeyId)
.where('d.local_date', '=', localDate)
.where('d.source', '=', source)
.executeTakeFirst();
}
/**
* Keeps a day, replacing the version kept for the same journey, day and
* source in the one statement, and answers its id. A replaced day keeps its
* id and the time it was first taken over.
*/
async upsertDay(day: JourneyRecordedDayWrite): Promise<number> {
const now = dbNow();
const written = await this.db()
.insertInto('journey_recorded_days')
.values({ ...day, created_at: now, updated_at: now })
.onConflict((oc) =>
oc.columns(['journey_id', 'local_date', 'source']).doUpdateSet({
source_kind: day.source_kind,
utc_offset_minutes: day.utc_offset_minutes,
window_from: day.window_from,
window_to: day.window_to,
segments: day.segments,
point_count: day.point_count,
distance_m: day.distance_m,
content_hash: day.content_hash,
truncated: day.truncated,
fetched_at: day.fetched_at,
imported_by: day.imported_by,
updated_at: now,
}),
)
.returning('id')
.executeTakeFirstOrThrow();
return written.id;
}
/** Drops the day a journey keeps for one source; false when it kept none. */
async deleteDay(journeyId: number, localDate: string, source: string): Promise<boolean> {
const result = await this.db()
.deleteFrom('journey_recorded_days')
.where('journey_id', '=', journeyId)
.where('local_date', '=', localDate)
.where('source', '=', source)
.executeTakeFirst();
return Number(result.numDeletedRows) > 0;
}
}
+2
View File
@@ -50,6 +50,7 @@ import { HealthModule } from './health/health.module';
import { HelpModule } from './help/help.module';
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 { JourneyModule } from './journey/journey.module';
import { TripJournalLinkModule } from './journey/trip-journal-link.module';
@@ -171,6 +172,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
AirtrailModule,
DawarichModule,
JourneyModule,
JourneyRecordingsModule,
TripJournalLinkModule,
CollectionsModule,
ShareModule,
@@ -1,19 +1,38 @@
import { Trips } from '../../db/entities/Trips.entity';
import { TripsRepository } from '../../db/repositories/Trips.repository';
import { DawarichClient, type DawarichCreds } from './dawarich.client';
import { bucketPointsByDay, bucketTracksByDay, countPoints, offsetMinutesOf } from './dawarich.helpers';
import { DomainError } from '../common/domain-error';
import { DawarichClient, DawarichError, type DawarichCreds } from './dawarich.client';
import { RECORDING_GAP, bucketPointsByDay, bucketTracksByDay, countPoints, offsetMinutesOf } from './dawarich.helpers';
import { DawarichService } from './dawarich.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { DAWARICH_TRACK_POINTS_PER_DAY, type DawarichTrack } from '@trek/shared';
import { DAWARICH_TRACK_POINTS_PER_DAY, type DawarichTrack, type DawarichTrackSegment } from '@trek/shared';
/** One local day of recording, read for a journey to keep (JRN-01). */
export interface RecordedDayFetch {
segments: DawarichTrackSegment[];
sourceKind: 'tracks' | 'points';
/** The zone the day was cut in, minutes east of UTC. */
utcOffsetMinutes: number;
offsetSource: 'source' | 'chosen';
/** The zone Dawarich records in, where its answer shows one. */
sourceOffsetMinutes: number | null;
window: { from: string; to: string };
fetchedAt: string;
truncated: boolean;
}
const HOUR_MS = 3_600_000;
/**
* The recorded route for a window, fetched on demand and never stored.
* The recorded route for a window, fetched on demand and never stored here.
*
* That is the point of the whole feature and the one rule it must not break:
* Dawarich owns the location archive. TREK draws the part of it somebody is
* looking at right now and forgets it again. There is no table here, no
* `route_geometry` written to a place, no background import.
* `route_geometry` written to a place, no background import. The one copy is
* a day a traveller takes over into a journey on purpose (`fetchDay`, JRN-01),
* and the journey keeps that, not this service.
*
* What there is instead is a short in-memory cache, because "update the line
* while the map is open" and "ask an instance for a month of GPS every few
@@ -161,6 +180,65 @@ export class DawarichTracksService {
};
}
/**
* One local day of recording, read fresh past the cache: what a journey keeps
* has to be what the instance says now, not what the map saw a minute ago.
*
* The day is cut in Dawarich's own zone when `useSourceOffset` asks for it and
* the answer reveals one (track times carry it, points do not), else in the
* zone given. The request spans every zone there is around the date, so the
* day is the same day whichever zone cuts it. A gap in the recording stays a
* gap. Refuses with a DomainError the controller and the MCP tool pass on:
* 409 `not_connected`, or the instance's own reason.
*/
async fetchDay(
userId: number,
date: string,
zone: { offsetMinutes: number; useSourceOffset: boolean },
): Promise<RecordedDayFetch> {
const creds = await this.dawarich.getCredentials(userId);
if (!creds) throw new DomainError(409, 'Dawarich is not connected', { details: { code: 'not_connected' } });
const dayStart = Date.parse(`${date}T00:00:00Z`);
const from = new Date(dayStart - 14 * HOUR_MS);
const to = new Date(dayStart + 36 * HOUR_MS);
const capabilities = await this.dawarich.getCapabilities(userId);
if (capabilities?.tracks !== false) {
try {
const { features, truncated } = await this.client.listTracks(creds, from, to);
const sourceOffset = sourceOffsetOf(features[0]?.properties?.start_at);
const offset = zoneOf(zone, sourceOffset);
const day = bucketTracksByDay(features, {
maxPointsPerDay: DAWARICH_TRACK_POINTS_PER_DAY,
offsetMinutes: offset.minutes,
}).find((d) => d.date === date);
if (day && day.segments.length > 0) {
return recordedDay(date, day.segments, 'tracks', offset, sourceOffset, truncated);
}
} catch {
// Points next, as for the overlay: an instance that cannot serve tracks
// can usually still serve what they are built from.
}
}
const offset = zoneOf(zone, null);
try {
const { points, truncated } = await this.client.listPoints(creds, from, to);
const day = bucketPointsByDay(points, offset.minutes, {
maxPointsPerDay: DAWARICH_TRACK_POINTS_PER_DAY,
gaps: RECORDING_GAP,
}).find((d) => d.date === date);
return recordedDay(date, day?.segments ?? [], 'points', offset, null, truncated);
} catch (err) {
if (err instanceof DawarichError) {
const status = err.code === 'unauthorized' || err.code === 'forbidden' ? 400 : 502;
throw new DomainError(status, err.message, { details: { code: err.code } });
}
throw err;
}
}
private remember(key: string, value: DawarichTrack): void {
if (this.cache.size >= DawarichTracksService.MAX_ENTRIES) {
const oldest = this.cache.keys().next().value;
@@ -177,6 +255,42 @@ export class DawarichTracksService {
}
}
/** The zone a Dawarich time names; null when it names none. */
function sourceOffsetOf(value: unknown): number | null {
if (typeof value !== 'string' || !/(Z|[+-]\d{2}:?\d{2})$/.test(value)) return null;
return offsetMinutesOf(value);
}
function zoneOf(
zone: { offsetMinutes: number; useSourceOffset: boolean },
sourceOffset: number | null,
): { minutes: number; source: 'source' | 'chosen' } {
return zone.useSourceOffset && sourceOffset !== null
? { minutes: sourceOffset, source: 'source' }
: { minutes: zone.offsetMinutes, source: 'chosen' };
}
function recordedDay(
date: string,
segments: DawarichTrackSegment[],
sourceKind: 'tracks' | 'points',
offset: { minutes: number; source: 'source' | 'chosen' },
sourceOffsetMinutes: number | null,
truncated: boolean,
): RecordedDayFetch {
const from = Date.parse(`${date}T00:00:00Z`) - offset.minutes * 60_000;
return {
segments,
sourceKind,
utcOffsetMinutes: offset.minutes,
offsetSource: offset.source,
sourceOffsetMinutes,
window: { from: new Date(from).toISOString(), to: new Date(from + 24 * HOUR_MS).toISOString() },
fetchedAt: new Date().toISOString(),
truncated,
};
}
function emptyTrack(): DawarichTrack {
return {
days: [],
+107 -12
View File
@@ -4,7 +4,7 @@ import type {
DawarichVisitRaw,
DawarichVisitedCountry,
} from './dawarich.client';
import type { DawarichTrackDay, DawarichTrackSegment } from '@trek/shared';
import { RECORDING_GAP_METERS, type DawarichTrackDay, type DawarichTrackSegment } from '@trek/shared';
import { createHash } from 'crypto';
@@ -41,9 +41,9 @@ export function offsetMinutesOf(iso: string): number {
return sign * (Number(match[2]) * 60 + Number(match[3]));
}
/** Local wall-clock milliseconds — the instant shifted into the string's own offset. */
function localMs(iso: string): number {
return Date.parse(iso) + offsetMinutesOf(iso) * 60_000;
/** Local wall-clock milliseconds — the instant shifted into the string's own offset, or into `offset` when given. */
function localMs(iso: string, offset?: number): number {
return Date.parse(iso) + (offset ?? offsetMinutesOf(iso)) * 60_000;
}
/** `YYYY-MM-DD` of a local wall-clock millisecond value. */
@@ -307,10 +307,61 @@ interface BucketOptions {
maxPointsPerDay: number;
/** Simplification tolerance in degrees. ~5e-5 is roughly five metres. */
epsilon: number;
/**
* Cut a day where the recording has a gap instead of drawing across it, and
* never join a day to the one before. Off for the live overlay, which has
* always joined its points up; on for a day a journey keeps (JRN-01).
*/
gaps?: GapRule;
/**
* Cut tracks at midnight in this zone (minutes east of UTC) rather than in
* the one their own times carry.
*/
offsetMinutes?: number;
}
const DEFAULT_BUCKET: BucketOptions = { maxPointsPerDay: 600, epsilon: 0.00005 };
/** When two recorded points are too far apart, in time and in space, to have been one movement. */
interface GapRule {
seconds: number;
meters: number;
}
/**
* Silence on its own is no gap: a phone that records only when it moves sends
* nothing for an hour at a café table and then goes on from the same spot.
* Silence that ends somewhere else is one, and the line between the two ends
* would be a way nobody can say was travelled.
*/
export const RECORDING_GAP: GapRule = { seconds: 15 * 60, meters: RECORDING_GAP_METERS };
interface TimedPoint {
lat: number;
lng: number;
ts: number;
}
/** Points in time order → the runs between the gaps of the recording. */
export function splitAtGaps<T extends TimedPoint>(points: T[], rule: GapRule): T[][] {
const runs: T[][] = [];
let run: T[] = [];
for (const point of points) {
const last = run[run.length - 1];
if (
last &&
point.ts - last.ts > rule.seconds &&
distanceMeters(last.lat, last.lng, point.lat, point.lng) > rule.meters
) {
runs.push(run);
run = [];
}
run.push(point);
}
if (run.length > 0) runs.push(run);
return runs;
}
/**
* Recorded points → one entry per local calendar day.
*
@@ -324,8 +375,8 @@ export function bucketPointsByDay(
offsetMinutes: number,
options: Partial<BucketOptions> = {},
): DawarichTrackDay[] {
const { maxPointsPerDay, epsilon } = { ...DEFAULT_BUCKET, ...options };
const byDay = new Map<string, Array<{ lat: number; lng: number; ts: number }>>();
const { maxPointsPerDay, epsilon, gaps } = { ...DEFAULT_BUCKET, ...options };
const byDay = new Map<string, TimedPoint[]>();
for (const point of points) {
const lat = toNumber(point.latitude);
@@ -346,6 +397,11 @@ export function bucketPointsByDay(
for (let d = 0; d < dates.length; d++) {
const date = dates[d]!;
const own = byDay.get(date)!.sort((a, b) => a.ts - b.ts);
if (gaps) {
const segments = runsAsSegments(splitAtGaps(own, gaps), own.length, { maxPointsPerDay, epsilon });
if (segments.length > 0) days.push({ date, segments });
continue;
}
// Stitch the previous day's last point on, so consecutive days join up
// rather than showing a jump the traveller never made.
const previous = d > 0 ? byDay.get(dates[d - 1]!) : undefined;
@@ -377,6 +433,40 @@ export function bucketPointsByDay(
return days;
}
/**
* The runs of one day as drawable segments, the day's point budget shared out
* by how many points each run brought. A run that thins to a single point is
* a fix, not a way, and is left out.
*/
function runsAsSegments(
runs: TimedPoint[][],
total: number,
{ maxPointsPerDay, epsilon }: Pick<BucketOptions, 'maxPointsPerDay' | 'epsilon'>,
): DawarichTrackSegment[] {
const segments: DawarichTrackSegment[] = [];
for (const run of runs) {
const budget = Math.max(2, Math.floor((maxPointsPerDay * run.length) / total));
const line = capPoints(
simplify(
run.map((p): [number, number] => [p.lat, p.lng]),
epsilon,
),
budget,
);
const first = run[0];
const last = run[run.length - 1];
if (line.length < 2 || !first || !last) continue;
segments.push({
points: line,
mode: null,
startedAt: new Date(first.ts * 1000).toISOString(),
endedAt: new Date(last.ts * 1000).toISOString(),
distanceMeters: null,
});
}
return segments;
}
/**
* Dawarich tracks → one entry per local calendar day.
*
@@ -391,7 +481,7 @@ export function bucketTracksByDay(
features: DawarichTrackFeature[],
options: Partial<BucketOptions> = {},
): DawarichTrackDay[] {
const { maxPointsPerDay, epsilon } = { ...DEFAULT_BUCKET, ...options };
const { maxPointsPerDay, epsilon, offsetMinutes } = { ...DEFAULT_BUCKET, ...options };
const byDay = new Map<string, DawarichTrackSegment[]>();
for (const feature of features) {
@@ -406,7 +496,7 @@ export function bucketTracksByDay(
const mode = typeof props?.dominant_mode === 'string' ? props.dominant_mode : null;
const distance = toNumber(props?.distance);
for (const piece of splitAtLocalMidnight(points, startedAt, endedAt)) {
for (const piece of splitAtLocalMidnight(points, startedAt, endedAt, offsetMinutes)) {
const line = capPoints(simplify(piece.points, epsilon), maxPointsPerDay);
if (line.length < 2) continue;
const segment: DawarichTrackSegment = {
@@ -442,9 +532,14 @@ interface TrackPiece {
whole: boolean;
}
function splitAtLocalMidnight(points: Array<[number, number]>, startedAt: string, endedAt: string): TrackPiece[] {
const startLocal = localMs(startedAt);
const endLocal = localMs(endedAt);
function splitAtLocalMidnight(
points: Array<[number, number]>,
startedAt: string,
endedAt: string,
zone?: number,
): TrackPiece[] {
const startLocal = localMs(startedAt, zone);
const endLocal = localMs(endedAt, zone);
const startDate = dateOfLocalMs(startLocal);
const endDate = dateOfLocalMs(endLocal);
@@ -468,7 +563,7 @@ function splitAtLocalMidnight(points: Array<[number, number]>, startedAt: string
return [{ date: startDate, points, startedAt, endedAt, whole: true }];
}
const offset = offsetMinutesOf(startedAt) * 60_000;
const offset = (zone ?? offsetMinutesOf(startedAt)) * 60_000;
const span = endLocal - startLocal;
const pieces: TrackPiece[] = [];
let cutIndex = 0;
+1 -1
View File
@@ -202,7 +202,7 @@ export class DawarichMcp {
@Tool({
name: 'get_dawarich_trip_track',
description:
"Fetch the route actually recorded during a trip, grouped by local day, straight from the caller's Dawarich instance. Each day carries its segments with start and end times and, where Dawarich classified it, how it was travelled. Use it to answer what route someone really took, or how a day's movement compares with what was planned. Nothing is stored in TREK — this is a live read of the recording.",
"Fetch the route actually recorded during a trip, grouped by local day, straight from the caller's Dawarich instance. Each day carries its segments with start and end times and, where Dawarich classified it, how it was travelled. Use it to answer what route someone really took, or how a day's movement compares with what was planned. This is a live read of the recording and stores nothing; a day is kept in a journey only when the traveller confirms it through save_journey_recorded_day.",
inputSchema: {
tripId: idSchema,
from: z
@@ -0,0 +1,85 @@
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 { JourneyRecordingPreviewDto, JourneyRecordingSaveDto } from './journey-recordings.dto';
import { JourneyRecordingsService } from './journey-recordings.service';
import {
Body,
Controller,
Delete,
Get,
Headers,
HttpCode,
HttpException,
Param,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import {
journeyRecordedDaysResponseSchema,
journeyRecordingDateSchema,
journeyRecordingPreviewSchema,
journeyRecordingSaveResultSchema,
successResponseSchema,
} from '@trek/shared';
/**
* The days of recorded route a journey keeps (JRN-01), at
* `/api/journeys/:id/recordings`. Reading them needs only access to the
* journey; previewing and keeping a day needs the right to edit it and the
* Dawarich addon, and reads the caller's own connection.
*/
@Controller('api/journeys/:id/recordings')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
export class JourneyRecordingsController {
constructor(private readonly recordings: JourneyRecordingsService) {}
@Get()
@ResponseContract(journeyRecordedDaysResponseSchema)
async list(@CurrentUser() user: User, @Param('id') id: string) {
return { days: await this.recordings.list(user.id, Number(id)) };
}
@Post('preview')
@HttpCode(200)
@ResponseContract(journeyRecordingPreviewSchema)
async preview(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyRecordingPreviewDto) {
return await this.recordings.preview(user.id, Number(id), body);
}
@Put(':date')
@ResponseContract(journeyRecordingSaveResultSchema)
async save(
@CurrentUser() user: User,
@Param('id') id: string,
@Param('date') date: string,
@Body() body: JourneyRecordingSaveDto,
@Headers('x-socket-id') socketId?: string,
) {
return await this.recordings.save(user.id, Number(id), dateParam(date), body, socketId);
}
@Delete(':date')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async remove(
@CurrentUser() user: User,
@Param('id') id: string,
@Param('date') date: string,
@Headers('x-socket-id') socketId?: string,
) {
await this.recordings.remove(user.id, Number(id), dateParam(date), socketId);
return { success: true as const };
}
}
function dateParam(raw: string): string {
if (!journeyRecordingDateSchema.safeParse(raw).success) throw new HttpException({ error: 'Invalid date' }, 400);
return raw;
}
@@ -0,0 +1,6 @@
import { journeyRecordingPreviewRequestSchema, journeyRecordingSaveRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class JourneyRecordingPreviewDto extends createZodDto(journeyRecordingPreviewRequestSchema) {}
export class JourneyRecordingSaveDto extends createZodDto(journeyRecordingSaveRequestSchema) {}
@@ -0,0 +1,111 @@
import { ADDON_IDS } from '../../addons';
import {
McpController,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
Tool,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate, type HasAddons } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { JourneyRecordingsService } from './journey-recordings.service';
import {
idSchema,
journeyRecordingDateSchema,
journeyRecordingPreviewRequestSchema,
journeyRecordingSaveRequestSchema,
type JourneyRecordedDay,
type JourneyRecordingPreviewRequest,
type JourneyRecordingSaveRequest,
} from '@trek/shared';
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
const dawarichAddonOn = addonGate(ADDON_IDS.DAWARICH);
/** Taking a day over reads Dawarich into a journey, so both addons have to be on. */
const bothAddonsOn = async (ctx: McpContext, self: HasAddons): Promise<boolean> =>
(await journeyAddonOn(ctx, self)) && (await dawarichAddonOn(ctx, self));
/**
* The recorded days a journey keeps (JRN-01) over MCP: the same service and
* the same journey access as `/api/journeys/:id/recordings`. The lines stay
* on the map; a tool answers with what a day covers, never its geometry.
*/
@McpController()
export class JourneyRecordingsMcp {
constructor(
private readonly recordings: JourneyRecordingsService,
readonly addons: AddonsService,
) {}
@Tool({
name: 'list_journey_recorded_days',
description:
'The days of route recorded in Dawarich that a journey keeps, one per local day: the zone the day was cut in, what it covers (distance, pieces, gaps without recording, modes, first and last time), whether the source was incomplete or the day still running when it was taken over, and whose recording it is. Kept days stay readable when Dawarich is unreachable.',
inputSchema: { journeyId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
access: { group: 'journey', mode: 'read' },
})
async listRecordedDays({ journeyId }: { journeyId: number }, ctx: McpContext) {
return ok({ days: (await this.recordings.list(ctx.userId, journeyId)).map(summary) });
}
@Tool({
name: 'preview_journey_recorded_day',
description:
"Read one local day of the route recorded in the caller's own Dawarich and show what a journey would keep, without keeping anything: the window the day runs in, what it covers, whether the journey already keeps that day and if it is the same, how many other people would see it, and the contentHash save_journey_recorded_day needs. utcOffsetMinutes is the zone to cut the day in; useSourceOffset cuts it in Dawarich's own zone where its answer shows one. Needs edit access to the journey.",
inputSchema: { journeyId: idSchema, ...journeyRecordingPreviewRequestSchema.shape },
// Reaches the caller's own Dawarich instance rather than TREK's database.
annotations: { ...TOOL_ANNOTATIONS_READONLY, openWorldHint: true },
when: bothAddonsOn,
access: { group: 'journey', mode: 'read' },
})
async previewRecordedDay(
{ journeyId, ...request }: { journeyId: number } & JourneyRecordingPreviewRequest,
ctx: McpContext,
) {
const preview = await this.recordings.preview(ctx.userId, journeyId, request);
const { segments: _segments, stored, ...rest } = preview;
return ok({ ...rest, stored: stored ? summary(stored) : null });
}
@Tool({
name: 'save_journey_recorded_day',
description:
"Keep one local day of the route recorded in the caller's Dawarich in a journey, after the traveller confirmed the preview. Send the utcOffsetMinutes and contentHash (as expectedHash) of preview_journey_recorded_day: when the recording changed since, nothing is kept and the answer says so. A day kept already exactly so is left as it is; a different version is replaced only with replace: true. Never changes an entry or a text of the journey. Everyone who can open the journey sees the route on its map.",
inputSchema: { journeyId: idSchema, date: journeyRecordingDateSchema, ...journeyRecordingSaveRequestSchema.shape },
annotations: { ...TOOL_ANNOTATIONS_WRITE, openWorldHint: true },
when: bothAddonsOn,
access: { group: 'journey', mode: 'write' },
})
async saveRecordedDay(
{ journeyId, date, ...request }: { journeyId: number; date: string } & JourneyRecordingSaveRequest,
ctx: McpContext,
) {
const { day, outcome } = await this.recordings.save(ctx.userId, journeyId, date, request);
return ok({ outcome, day: summary(day) });
}
@Tool({
name: 'delete_journey_recorded_day',
description:
'Drop the recorded route a journey keeps for one local day. Its entries and texts stay as they are, and Dawarich keeps its own recording. Needs edit access to the journey.',
inputSchema: { journeyId: idSchema, date: journeyRecordingDateSchema },
annotations: TOOL_ANNOTATIONS_DELETE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async deleteRecordedDay({ journeyId, date }: { journeyId: number; date: string }, ctx: McpContext) {
await this.recordings.remove(ctx.userId, journeyId, date);
return ok({ success: true });
}
}
/** A kept day without its geometry, which is the whole payload and belongs on a map. */
function summary(day: JourneyRecordedDay) {
const { segments: _segments, ...rest } = day;
return rest;
}
@@ -0,0 +1,20 @@
import { AddonsModule } from '../addons/addons.module';
import { DawarichModule } from '../integrations/dawarich.module';
import { JourneyDomainModule } from '../journey/journey-domain.module';
import { JourneyRecordingsController } from './journey-recordings.controller';
import { JourneyRecordingsMcp } from './journey-recordings.mcp';
import { JourneyRecordingsService } from './journey-recordings.service';
import { Module } from '@nestjs/common';
/**
* A journey keeping the route recorded on its days (JRN-01): taking a day over
* from the caller's Dawarich connection, its routes and its MCP tools. The
* days themselves belong to the journey domain; this module only brings them
* in from Dawarich, so neither of the two has to import the other.
*/
@Module({
imports: [JourneyDomainModule, DawarichModule, AddonsModule],
controllers: [JourneyRecordingsController],
providers: [JourneyRecordingsService, JourneyRecordingsMcp],
})
export class JourneyRecordingsModule {}
@@ -0,0 +1,140 @@
import { ADDON_IDS } from '../../addons';
import { AddonsService } from '../addons/addons.service';
import { DomainError, conflict, forbidden, notFound } from '../common/domain-error';
import { DawarichTracksService } from '../integrations/dawarich-tracks.service';
import { JourneyDomainService } from '../journey/journey-domain.service';
import { JourneyRecordedDaysService } from '../journey/journey-recorded-days.service';
import { Injectable } from '@nestjs/common';
import {
recordingStats,
type JourneyRecordedDay,
type JourneyRecordingPreview,
type JourneyRecordingPreviewRequest,
type JourneyRecordingSaveRequest,
type JourneyRecordingSaveResult,
} from '@trek/shared';
/**
* Taking a day's recorded route over into a journey (JRN-01): a live preview
* of the day from the caller's own Dawarich connection, then, on their word,
* a copy the journey keeps.
*
* The preview writes nothing. The save reads the day again and keeps it only
* when it is still the one previewed (its hash), so a recording that grew in
* between is shown again before it is kept. A failed read throws before
* anything is written, so the version a journey kept stays as it was. The
* same day taken over twice keeps one version; a different one replaces it
* only when asked to, and never touches an entry or a text of the journey.
*
* Whoever may edit the journey may keep their own recording in it; everyone
* who can open the journey sees it on the map, which the preview says.
*/
@Injectable()
export class JourneyRecordingsService {
constructor(
private readonly journeys: JourneyDomainService,
private readonly recordedDays: JourneyRecordedDaysService,
private readonly tracks: DawarichTracksService,
private readonly addons: AddonsService,
) {}
/** The days a journey keeps, for anyone who can open it. Needs no Dawarich. */
async list(userId: number, journeyId: number): Promise<JourneyRecordedDay[]> {
if (!(await this.journeys.canAccessJourney(journeyId, userId))) throw notFound('Journey not found');
return await this.recordedDays.list(journeyId);
}
async preview(
userId: number,
journeyId: number,
request: JourneyRecordingPreviewRequest,
): Promise<JourneyRecordingPreview> {
const journey = await this.editable(journeyId, userId);
await this.requireDawarich();
const day = await this.tracks.fetchDay(userId, request.date, {
offsetMinutes: request.utcOffsetMinutes,
useSourceOffset: request.useSourceOffset ?? false,
});
const contentHash = day.segments.length > 0 ? this.recordedDays.hashOf(day.segments, day.utcOffsetMinutes) : null;
const stored = await this.recordedDays.find(journeyId, request.date);
return {
journey: { id: journey.id, title: journey.title },
date: request.date,
utcOffsetMinutes: day.utcOffsetMinutes,
offsetSource: day.offsetSource,
sourceOffsetMinutes: day.sourceOffsetMinutes,
window: day.window,
sourceKind: day.sourceKind,
segments: day.segments,
stats: recordingStats(day.segments),
truncated: day.truncated,
provisional: Date.parse(day.fetchedAt) < Date.parse(day.window.to),
fetchedAt: day.fetchedAt,
contentHash,
stored,
sameAsStored: stored !== null && stored.contentHash === contentHash,
audience: await this.recordedDays.audience(journeyId, userId),
};
}
async save(
userId: number,
journeyId: number,
date: string,
request: JourneyRecordingSaveRequest,
socketId?: string,
): Promise<JourneyRecordingSaveResult> {
await this.editable(journeyId, userId);
await this.requireDawarich();
const day = await this.tracks.fetchDay(userId, date, {
offsetMinutes: request.utcOffsetMinutes,
useSourceOffset: false,
});
if (day.segments.length === 0) {
throw new DomainError(422, 'Dawarich recorded nothing on that day', { details: { code: 'recording_empty' } });
}
const contentHash = this.recordedDays.hashOf(day.segments, day.utcOffsetMinutes);
if (contentHash !== request.expectedHash) {
throw conflict('The recording changed since the preview', { code: 'recording_changed' });
}
const stored = await this.recordedDays.find(journeyId, date);
if (stored?.contentHash === contentHash) return { day: stored, outcome: 'unchanged' };
if (stored && !request.replace) {
throw conflict('The journey already keeps another recording of that day', { code: 'recording_exists' });
}
const kept = await this.recordedDays.keep(journeyId, userId, {
date,
sourceKind: day.sourceKind,
utcOffsetMinutes: day.utcOffsetMinutes,
window: day.window,
segments: day.segments,
truncated: day.truncated,
fetchedAt: day.fetchedAt,
contentHash,
});
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:recording:updated', { date }, socketId);
return { day: kept, outcome: stored ? 'replaced' : 'created' };
}
/** Drops the day a journey keeps. Needs no Dawarich: a kept day stays removable once the connection is gone. */
async remove(userId: number, journeyId: number, date: string, socketId?: string): Promise<void> {
await this.editable(journeyId, userId);
if (!(await this.recordedDays.remove(journeyId, date))) throw notFound('No recording kept for that day');
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:recording:updated', { date }, socketId);
}
private async editable(journeyId: number, userId: number) {
const journey = await this.journeys.canAccessJourney(journeyId, userId);
if (!journey) throw notFound('Journey not found');
if (!(await this.journeys.canEdit(journeyId, userId))) throw forbidden('Not allowed');
return journey;
}
private async requireDawarich(): Promise<void> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.DAWARICH))) {
throw notFound('Dawarich is not enabled', { code: 'addon_disabled' });
}
}
}
@@ -2,6 +2,7 @@ import { JourneyContributors } from '../../db/entities/JourneyContributors.entit
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
import { JourneyRecordedDays } from '../../db/entities/JourneyRecordedDays.entity';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import { JourneyTrips } from '../../db/entities/JourneyTrips.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
@@ -12,6 +13,7 @@ import { TrekPhotosModule } from '../photos/trek-photos.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { SettingsModule } from '../settings/settings.module';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyRecordedDaysService } from './journey-recorded-days.service';
import { JourneyShareService } from './journey-share.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
@@ -61,6 +63,9 @@ import { Module } from '@nestjs/common';
* for JS1-JS15, plus reuses the already-registered `JourneysRepository` for
* JS8/JS12 — no other module needed touching since both were already in
* this array or this module's own provider graph.
* `JourneyRecordedDays` (JRN-01) is the days of recorded route a journey
* keeps; `JourneyRecordedDaysService` reads and writes them here, so the map
* needs nothing of the integration they were taken over from.
*/
@Module({
imports: [
@@ -78,9 +83,10 @@ import { Module } from '@nestjs/common';
JourneyEntryPhotos,
Places,
JourneyShareTokens,
JourneyRecordedDays,
]),
],
providers: [JourneyDomainService, JourneyShareService],
exports: [JourneyDomainService, JourneyShareService],
providers: [JourneyDomainService, JourneyShareService, JourneyRecordedDaysService],
exports: [JourneyDomainService, JourneyShareService, JourneyRecordedDaysService],
})
export class JourneyDomainModule {}
@@ -0,0 +1,118 @@
import { JourneyRecordedDays } from '../../db/entities/JourneyRecordedDays.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import { JOURNEY_RECORDED_DAY_SEGMENTS } from '../../db/json-columns';
import type {
JourneyRecordedDayRow,
JourneyRecordedDaysRepository,
} from '../../db/repositories/JourneyRecordedDays.repository';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { parseDbTimestamp } from '../../db/types';
import { decodeJson } from '../../utils/json-column';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { recordingStats, type DawarichTrackSegment, type JourneyRecordedDay } from '@trek/shared';
import crypto from 'crypto';
/** A day's recording as it is handed over to be kept. */
interface RecordingToKeep {
date: string;
sourceKind: 'tracks' | 'points';
utcOffsetMinutes: number;
window: { from: string; to: string };
segments: DawarichTrackSegment[];
truncated: boolean;
fetchedAt: string;
contentHash: string;
}
const SOURCE = 'dawarich';
/**
* The recorded days a journey keeps (JRN-01). The journey owns them, so its
* map can draw them without the integration they came from; taking a day
* over from Dawarich is `journey-recordings`' part.
*/
@Injectable()
export class JourneyRecordedDaysService {
constructor(
@InjectRepository(JourneyRecordedDays) private readonly days: JourneyRecordedDaysRepository,
@InjectRepository(Journeys) private readonly journeys: JourneysRepository,
) {}
/**
* What a recording says, as one value: equal hashes are the same line cut in
* the same zone, so taking it over again keeps nothing new.
*/
hashOf(segments: DawarichTrackSegment[], utcOffsetMinutes: number): string {
return crypto
.createHash('sha256')
.update(`${utcOffsetMinutes}|${JSON.stringify(segments)}`)
.digest('hex');
}
async list(journeyId: number): Promise<JourneyRecordedDay[]> {
return (await this.days.listForJourney(journeyId)).map(toRecordedDay);
}
async find(journeyId: number, date: string): Promise<JourneyRecordedDay | null> {
const row = await this.days.findDay(journeyId, date, SOURCE);
return row ? toRecordedDay(row) : null;
}
/** Keeps a day's recording, replacing what the journey kept for that day, and answers it as kept. */
async keep(journeyId: number, userId: number, recording: RecordingToKeep): Promise<JourneyRecordedDay> {
const stats = recordingStats(recording.segments);
await this.days.upsertDay({
journey_id: journeyId,
local_date: recording.date,
source: SOURCE,
source_kind: recording.sourceKind,
utc_offset_minutes: recording.utcOffsetMinutes,
window_from: recording.window.from,
window_to: recording.window.to,
segments: JSON.stringify(recording.segments),
point_count: stats.pointCount,
distance_m: stats.distanceMeters,
content_hash: recording.contentHash,
truncated: recording.truncated ? 1 : 0,
fetched_at: recording.fetchedAt,
imported_by: userId,
});
const kept = await this.find(journeyId, recording.date);
if (!kept) throw new Error(`Recorded day ${recording.date} of journey ${journeyId} vanished after its write`);
return kept;
}
async remove(journeyId: number, date: string): Promise<boolean> {
return await this.days.deleteDay(journeyId, date, SOURCE);
}
/** How many people besides `userId` can open the journey, and so would see its map. */
async audience(journeyId: number, userId: number): Promise<number> {
return (await this.journeys.listRecipientUserIds(journeyId)).filter((id) => id !== userId).length;
}
}
function toRecordedDay(row: JourneyRecordedDayRow): JourneyRecordedDay {
const segments = decodeJson(JOURNEY_RECORDED_DAY_SEGMENTS, row.segments, `recorded day ${row.id}`);
return {
id: row.id,
date: row.local_date,
source: SOURCE,
sourceKind: row.source_kind === 'tracks' ? 'tracks' : 'points',
utcOffsetMinutes: row.utc_offset_minutes,
window: { from: row.window_from, to: row.window_to },
segments,
stats: recordingStats(segments),
truncated: row.truncated === 1,
provisional: Date.parse(row.fetched_at) < Date.parse(row.window_to),
fetchedAt: row.fetched_at,
contentHash: row.content_hash,
importedBy:
row.imported_by !== null && row.imported_by_username !== null
? { id: row.imported_by, username: row.imported_by_username }
: null,
savedAt: (parseDbTimestamp(row.updated_at) ?? new Date(0)).toISOString(),
};
}
@@ -0,0 +1,295 @@
/**
* Recorded days a journey keeps (JRN-01), through the real AddonGuard and
* JwtAuthGuard against a migrated and seeded temp SQLite db, every answer
* checked against its response contract. The Dawarich client is the one
* thing replaced: a test never opens a socket to a location archive. The
* broadcasts go to a FakeRealtimeService.
*
* Fixtures: user 1 owns journey 7 and has a Dawarich connection, user 2 is an
* editor of it with no connection, user 3 a viewer, user 4 has no access.
*
* The walk: preview, keep, read the day back once the connection is gone,
* take the same day over again without a second copy, replace it on purpose,
* keep the version when Dawarich fails, and drop it.
*/
import { DawarichConnections } from '../../src/db/entities/DawarichConnections.entity';
import { JourneyRecordedDays } from '../../src/db/entities/JourneyRecordedDays.entity';
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { DawarichClient, DawarichError } from '../../src/nest/integrations/dawarich.client';
import { JourneyRecordingsModule } from '../../src/nest/journey-recordings/journey-recordings.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';
import { countRows, deleteRows, insertRow } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
const client = {
probe: vi.fn(),
listVisits: vi.fn(),
listTracks: vi.fn(),
listPoints: vi.fn(),
listVisitedCities: vi.fn(),
findVisitsNear: vi.fn(),
};
let orm: TestOrm;
let journeyId: number;
const OWNER = 1;
const EDITOR = 2;
const VIEWER = 3;
const OUTSIDER = 4;
const DAY = '2026-05-14';
/** A walk across Venice on the 14th, in the zone Dawarich records in. */
function walk(endLng = 12.3218) {
return {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[12.3388, 45.434],
[endLng, 45.4364],
],
},
properties: {
start_at: `${DAY}T09:00:00+02:00`,
end_at: `${DAY}T09:40:00+02:00`,
dominant_mode: 'walking',
distance: 1500,
},
};
}
describe('Journey recordings e2e (real guards + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
JourneyRecordingsModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.overrideProvider(DawarichClient)
.useValue(client)
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const base = () => `/api/journeys/${journeyId}/recordings`;
const preview = (userId = OWNER) =>
request(server)
.post(`${base()}/preview`)
.set(as(userId))
.send({ date: DAY, utcOffsetMinutes: 0, useSourceOffset: true });
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: the session cookies sign for exactly these users.
const user = (id: number, username: string) =>
makeUser(orm, { id, username, email: `${username}@example.test`, role: 'user', password_version: 0 });
await user(OWNER, 'marta');
await user(EDITOR, 'jonas');
await user(VIEWER, 'viewer');
await user(OUTSIDER, 'outsider');
const journey = await makeJourney(orm, OWNER, { title: 'Venice' });
journeyId = journey.id;
await addJourneyContributor(orm, journeyId, EDITOR, 'editor');
await addJourneyContributor(orm, journeyId, VIEWER, 'viewer');
app = await build();
server = app.getHttpServer();
});
beforeEach(async () => {
await setAddonEnabled(orm, 'journey', true);
await setAddonEnabled(orm, 'dawarich', true);
await deleteRows(orm, JourneyRecordedDays);
await deleteRows(orm, DawarichConnections);
await insertRow(orm, DawarichConnections, {
user: OWNER,
url: 'https://dawarich.example',
api_key: encrypt_api_key('secret-key'),
});
for (const fn of Object.values(client)) fn.mockReset();
client.listTracks.mockResolvedValue({ features: [walk()], truncated: false });
client.listPoints.mockResolvedValue({ points: [], truncated: false });
realtime.broadcastToUserMock.mockClear();
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('answers 404 with the Journey addon off before asking who the caller is, and 401 without a session', async () => {
await setAddonEnabled(orm, 'journey', false);
expect((await request(server).get(base())).status).toBe(404);
await setAddonEnabled(orm, 'journey', true);
expect((await request(server).get(base())).status).toBe(401);
});
it('previews the day for the journey without keeping it, then keeps it on the word of the traveller', async () => {
const shown = await preview();
expect(shown.status).toBe(200);
expect(shown.body).toMatchObject({
journey: { id: journeyId, title: 'Venice' },
date: DAY,
utcOffsetMinutes: 120,
offsetSource: 'source',
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
sourceKind: 'tracks',
stats: { distanceMeters: 1500, segmentCount: 1, gapCount: 0, modes: ['walking'] },
stored: null,
audience: 2,
});
expect(await countRows(orm, JourneyRecordedDays)).toBe(0);
const kept = await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.set('X-Socket-Id', '11')
.send({ utcOffsetMinutes: 120, expectedHash: shown.body.contentHash });
expect(kept.status).toBe(200);
expect(kept.body).toMatchObject({ outcome: 'created', day: { date: DAY, importedBy: { username: 'marta' } } });
expect(realtime.broadcastToUserMock).toHaveBeenCalledWith(
VIEWER,
{ type: 'journey:recording:updated', journeyId, date: DAY },
'11',
);
});
it('keeps the day readable for every member once the connection is gone, and never copies it twice', async () => {
const shown = await preview();
const body = { utcOffsetMinutes: 120, expectedHash: shown.body.contentHash };
await request(server).put(`${base()}/${DAY}`).set(as(OWNER)).send(body);
const again = await request(server).put(`${base()}/${DAY}`).set(as(OWNER)).send(body);
expect(again.status).toBe(200);
expect(again.body.outcome).toBe('unchanged');
expect(await countRows(orm, JourneyRecordedDays)).toBe(1);
await deleteRows(orm, DawarichConnections);
await setAddonEnabled(orm, 'dawarich', false);
client.listTracks.mockReset();
const listed = await request(server).get(base()).set(as(VIEWER));
expect(listed.status).toBe(200);
expect(listed.body.days).toHaveLength(1);
expect(listed.body.days[0]).toMatchObject({ date: DAY, segments: [{ mode: 'walking' }] });
expect(client.listTracks).not.toHaveBeenCalled();
expect((await request(server).get(base()).set(as(OUTSIDER))).status).toBe(404);
});
it('replaces a kept day only when asked, and a failing Dawarich leaves the kept version as it was', async () => {
const first = await preview();
await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.send({ utcOffsetMinutes: 120, expectedHash: first.body.contentHash });
client.listTracks.mockResolvedValue({ features: [walk(12.3), walk(12.31)], truncated: false });
const grown = await preview();
expect(grown.body).toMatchObject({ sameAsStored: false, stored: { stats: { segmentCount: 1 } } });
const body = { utcOffsetMinutes: 120, expectedHash: grown.body.contentHash };
const refused = await request(server).put(`${base()}/${DAY}`).set(as(OWNER)).send(body);
expect(refused.status).toBe(409);
expect(refused.body).toEqual({
error: 'The journey already keeps another recording of that day',
code: 'recording_exists',
});
client.listTracks.mockRejectedValue(new DawarichError('server_error', 'Dawarich answered HTTP 500', 500));
client.listPoints.mockRejectedValue(new DawarichError('server_error', 'Dawarich answered HTTP 500', 500));
const failed = await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.send({ ...body, replace: true });
expect(failed.status).toBe(502);
expect(failed.body).toMatchObject({ code: 'server_error' });
const unchanged = await request(server).get(base()).set(as(OWNER));
expect(unchanged.body.days[0].contentHash).toBe(first.body.contentHash);
client.listTracks.mockResolvedValue({ features: [walk(12.3), walk(12.31)], truncated: false });
const replaced = await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.send({ ...body, replace: true });
expect(replaced.status).toBe(200);
expect(replaced.body.outcome).toBe('replaced');
expect(await countRows(orm, JourneyRecordedDays)).toBe(1);
});
it('an editor without a connection is told so, a viewer may not preview, and a bad body or day is a 400', async () => {
const unconnected = await preview(EDITOR);
expect(unconnected.status).toBe(409);
expect(unconnected.body).toEqual({ error: 'Dawarich is not connected', code: 'not_connected' });
expect((await preview(VIEWER)).status).toBe(403);
expect((await preview(OUTSIDER)).status).toBe(404);
const badBody = await request(server)
.post(`${base()}/preview`)
.set(as(OWNER))
.send({ date: DAY, utcOffsetMinutes: 2000 });
expect(badBody.status).toBe(400);
const badDay = await request(server)
.put(`${base()}/2026-13-01`)
.set(as(OWNER))
.send({ utcOffsetMinutes: 0, expectedHash: 'a'.repeat(64) });
expect(badDay.status).toBe(400);
expect(badDay.body).toEqual({ error: 'Invalid date' });
});
it('drops a kept day for an editor, with Dawarich off, and a second drop is a 404', async () => {
const shown = await preview();
await request(server)
.put(`${base()}/${DAY}`)
.set(as(OWNER))
.send({ utcOffsetMinutes: 120, expectedHash: shown.body.contentHash });
await setAddonEnabled(orm, 'dawarich', false);
expect((await request(server).delete(`${base()}/${DAY}`).set(as(VIEWER))).status).toBe(403);
const dropped = await request(server).delete(`${base()}/${DAY}`).set(as(EDITOR));
expect(dropped.status).toBe(200);
expect(dropped.body).toEqual({ success: true });
expect(await countRows(orm, JourneyRecordedDays)).toBe(0);
expect((await request(server).delete(`${base()}/${DAY}`).set(as(EDITOR))).status).toBe(404);
});
});
+4 -3
View File
@@ -46,14 +46,15 @@ describe('ALL_ENTITIES', () => {
* + tour_activity_exclusions, the tours a user left out of their own activity sums
* + collection_tours, the whole tours a collection keeps
* + tour_packing_links, the packing list or category a tour points at
* + tour_source_hints, what the wanderer watch found about a snapshot's source)
* + tour_source_hints, what the wanderer watch found about a snapshot's source
* + journey_recorded_days, the recorded route a journey keeps per day)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 149 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(149);
it('ENT-003: exactly 150 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(150);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -43,7 +43,9 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// + collection_tours: id, collection_id, name, waypoints, tour_type, origin, source_trip_title, source_tour_name
// (a kept tour is only ever written whole, from the tour it was saved from).
// + tour_source_hints: user_id (a hint is only ever written for the user whose snapshot it is about).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 519;
// + journey_recorded_days: id, journey_id, local_date, source_kind, utc_offset_minutes, window_from,
// window_to, segments, point_count, content_hash, fetched_at (a kept day is only ever written whole).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 530;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
@@ -82,6 +82,7 @@ const UNNUMBERED = [
'Migration20200101046130_snowshoeing_and_winter_hiking_are_ski_disciplines',
'Migration20200101046140_tours_are_on_for_every_install',
'Migration20200101046150_a_ski_tour_keeps_its_piste_router_options',
'Migration20200101046160_a_journey_keeps_its_recorded_days',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,155 @@
/**
* `JourneyRecordedDaysRepository` (JRN-01): a day a journey keeps written
* whole, read back with the name of whose recording it is, one version per
* journey, day and source with a second write replacing the first in place,
* removed on its own, gone with its journey and kept past its importer.
*/
import { JourneyRecordedDays } from '../../../../src/db/entities/JourneyRecordedDays.entity';
import { Journeys } from '../../../../src/db/entities/Journeys.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type {
JourneyRecordedDaysRepository,
JourneyRecordedDayWrite,
} from '../../../../src/db/repositories/JourneyRecordedDays.repository';
import { dbNow } from '../../../../src/db/types';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeJourney } from '../../../helpers/factories/journeys';
import { countRows, deleteRows, updateRows } 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 days: JourneyRecordedDaysRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
days = t.repo(JourneyRecordedDays);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
async function journey() {
const { user } = await makeUser(t, { username: 'marta' });
const j = await makeJourney(t, user.id);
return { user, journey: j };
}
function day(journeyId: number, importedBy: number | null, overrides: Partial<JourneyRecordedDayWrite> = {}) {
return {
journey_id: journeyId,
local_date: '2026-05-14',
source: 'dawarich',
source_kind: 'tracks',
utc_offset_minutes: 120,
window_from: '2026-05-13T22:00:00.000Z',
window_to: '2026-05-14T22:00:00.000Z',
segments: '[{"points":[[45.43,12.33],[45.44,12.34]],"mode":"walking"}]',
point_count: 2,
distance_m: 1300,
content_hash: 'a'.repeat(64),
truncated: 0,
fetched_at: '2026-05-15T08:00:00.000Z',
imported_by: importedBy,
...overrides,
} satisfies JourneyRecordedDayWrite;
}
describe('JourneyRecordedDaysRepository', () => {
it('JRDAYS-001: keeps a day whole and reads it back with the name of whose recording it is', async () => {
const { user, journey: j } = await journey();
const id = await days.upsertDay(day(j.id, user.id));
const row = await days.findDay(j.id, '2026-05-14', 'dawarich');
expect(row).toMatchObject({
id,
journey_id: j.id,
local_date: '2026-05-14',
source_kind: 'tracks',
utc_offset_minutes: 120,
window_from: '2026-05-13T22:00:00.000Z',
point_count: 2,
distance_m: 1300,
truncated: 0,
imported_by: user.id,
imported_by_username: 'marta',
});
expect(row?.created_at).toEqual(expect.any(String));
expect(await days.findDay(j.id, '2026-05-15', 'dawarich')).toBeUndefined();
});
it('JRDAYS-002: a second write of the same day replaces the first in place, keeping its id', async () => {
const { user, journey: j } = await journey();
const first = await days.upsertDay(day(j.id, user.id));
const second = await days.upsertDay(
day(j.id, user.id, { content_hash: 'b'.repeat(64), point_count: 40, source_kind: 'points', distance_m: null }),
);
expect(second).toBe(first);
expect(await countRows(t, JourneyRecordedDays, {})).toBe(1);
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({
content_hash: 'b'.repeat(64),
point_count: 40,
source_kind: 'points',
distance_m: null,
});
});
it('JRDAYS-003: lists the days of one journey earliest first, and only its own', async () => {
const { user, journey: j } = await journey();
const other = await makeJourney(t, user.id);
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-16' }));
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-14' }));
await days.upsertDay(day(other.id, user.id, { local_date: '2026-05-15' }));
expect((await days.listForJourney(j.id)).map((row) => row.local_date)).toEqual(['2026-05-14', '2026-05-16']);
expect(await days.listForJourney(9999)).toEqual([]);
});
it('JRDAYS-004: removes one day and says whether there was one', async () => {
const { user, journey: j } = await journey();
await days.upsertDay(day(j.id, user.id));
await days.upsertDay(day(j.id, user.id, { local_date: '2026-05-15' }));
expect(await days.deleteDay(j.id, '2026-05-14', 'dawarich')).toBe(true);
expect(await days.deleteDay(j.id, '2026-05-14', 'dawarich')).toBe(false);
expect((await days.listForJourney(j.id)).map((row) => row.local_date)).toEqual(['2026-05-15']);
});
it('JRDAYS-005: a day goes with its journey and outlives the account that took it over', async () => {
const { journey: j } = await journey();
const { user: editor } = await makeUser(t);
await days.upsertDay(day(j.id, editor.id));
await deleteRows(t, Users, { id: editor.id });
expect(await days.findDay(j.id, '2026-05-14', 'dawarich')).toMatchObject({
imported_by: null,
imported_by_username: null,
});
await deleteRows(t, Journeys, { id: j.id });
expect(await countRows(t, JourneyRecordedDays, {})).toBe(0);
});
it('JRDAYS-006: a replacing write stamps the time it was kept again', async () => {
const { user, journey: j } = await journey();
await days.upsertDay(day(j.id, user.id));
const longAgo = dbNow(new Date('2020-01-01T00:00:00Z'));
await updateRows(t, JourneyRecordedDays, { journey: j.id }, { created_at: longAgo, updated_at: longAgo });
await days.upsertDay(day(j.id, user.id, { content_hash: 'c'.repeat(64) }));
const row = await days.findDay(j.id, '2026-05-14', 'dawarich');
expect(row?.created_at).toBe(longAgo);
expect(row?.updated_at).not.toBe(longAgo);
});
});
@@ -1,6 +1,6 @@
/**
* DawarichTracksService unit tests, DAWARICH-TRACKS-001 through
* DAWARICH-TRACKS-053. The service is built with `new` and every collaborator
* DAWARICH-TRACKS-061. The service is built with `new` and every collaborator
* is a plain mock: no Nest container, no database, no socket. The helpers it
* delegates the actual geometry to (`bucketPointsByDay`, `bucketTracksByDay`)
* are the real ones, because what this service decides is *which* of them runs
@@ -43,6 +43,7 @@
* can name rather than merely "some string".
*/
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
import { DomainError } from '../../../src/nest/common/domain-error';
import { DawarichTracksService } from '../../../src/nest/integrations/dawarich-tracks.service';
import { DawarichError } from '../../../src/nest/integrations/dawarich.client';
import type {
@@ -713,3 +714,154 @@ describe('DawarichTracksService source selection', () => {
expect(track.pointCount).toBe(5);
});
});
// ---------------------------------------------------------------------------
// fetchDay: one local day for a journey to keep (JRN-01)
// ---------------------------------------------------------------------------
describe('DawarichTracksService.fetchDay', () => {
const CHOSEN_UTC = { offsetMinutes: 0, useSourceOffset: false };
it('DAWARICH-TRACKS-054: without a connection it refuses with not_connected and asks nobody', async () => {
const h = harness({ creds: null });
const refusal = await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC).catch((err: unknown) => err);
expect(refusal).toBeInstanceOf(DomainError);
expect((refusal as DomainError).getStatus()).toBe(409);
expect((refusal as DomainError).toBody()).toEqual({ error: 'Dawarich is not connected', code: 'not_connected' });
expect(h.listTracks).not.toHaveBeenCalled();
expect(h.listPoints).not.toHaveBeenCalled();
});
it('DAWARICH-TRACKS-055: asks one window wide enough for every zone and cuts the day in the zone chosen', async () => {
const h = harness({ capabilities: CAPABILITIES });
h.listTracks.mockResolvedValue({
features: [feature({ start_at: '2026-05-01T10:00:00+02:00', end_at: '2026-05-01T12:00:00+02:00' })],
truncated: false,
});
const day = await h.service.fetchDay(USER, '2026-05-01', { offsetMinutes: 120, useSourceOffset: false });
const [, from, to] = h.listTracks.mock.calls[0] as [DawarichCreds, Date, Date];
expect(from.toISOString()).toBe('2026-04-30T10:00:00.000Z');
expect(to.toISOString()).toBe('2026-05-02T12:00:00.000Z');
expect(day).toMatchObject({
sourceKind: 'tracks',
utcOffsetMinutes: 120,
offsetSource: 'chosen',
sourceOffsetMinutes: 120,
window: { from: '2026-04-30T22:00:00.000Z', to: '2026-05-01T22:00:00.000Z' },
fetchedAt: NOW_ISO,
truncated: false,
});
expect(day.segments).toHaveLength(1);
expect(day.segments[0]).toMatchObject({ mode: 'car', distanceMeters: 41_000 });
});
it('DAWARICH-TRACKS-056: asked to, it cuts the day in the zone Dawarich records in, which can move a track onto it', async () => {
const h = harness({ capabilities: CAPABILITIES });
// 01:00 in Berlin is 23:00 the evening before in UTC.
h.listTracks.mockResolvedValue({
features: [feature({ start_at: '2026-05-01T01:00:00+02:00', end_at: '2026-05-01T01:40:00+02:00' })],
truncated: false,
});
const own = await h.service.fetchDay(USER, '2026-05-01', { offsetMinutes: 0, useSourceOffset: true });
expect(own).toMatchObject({ sourceKind: 'tracks', utcOffsetMinutes: 120, offsetSource: 'source' });
expect(own.segments).toHaveLength(1);
// Cut in UTC instead, the track belongs to the day before, and the points
// fallback finds nothing on this one either.
const utc = await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
expect(utc).toMatchObject({ sourceKind: 'points', utcOffsetMinutes: 0, offsetSource: 'chosen', segments: [] });
});
it('DAWARICH-TRACKS-057: points keep the gaps of the recording: a silence that ends elsewhere is two pieces, not a line', async () => {
const h = harness({ capabilities: { ...CAPABILITIES, tracks: false } });
h.listPoints.mockResolvedValue({
points: [
point(52.0, 13.0, '2026-05-01T10:00:00Z'),
point(52.002, 13.002, '2026-05-01T10:05:00Z'),
// Three hours of nothing, then six kilometres away.
point(52.05, 13.05, '2026-05-01T13:05:00Z'),
point(52.052, 13.052, '2026-05-01T13:10:00Z'),
],
truncated: false,
});
const day = await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
expect(day.sourceKind).toBe('points');
expect(day.sourceOffsetMinutes).toBeNull();
expect(day.segments.map((segment) => segment.points)).toEqual([
[
[52.0, 13.0],
[52.002, 13.002],
],
[
[52.05, 13.05],
[52.052, 13.052],
],
]);
});
it('DAWARICH-TRACKS-058: a silence that ends where it began is no gap, and nothing of the day before is joined on', async () => {
const h = harness({ capabilities: { ...CAPABILITIES, tracks: false } });
h.listPoints.mockResolvedValue({
points: [
point(51.0, 12.0, '2026-04-30T22:00:00Z'),
point(52.0, 13.0, '2026-05-01T10:00:00Z'),
// An hour at a table in a cafe, then on from the same spot.
point(52.0001, 13.0001, '2026-05-01T11:00:00Z'),
point(52.01, 13.01, '2026-05-01T11:10:00Z'),
],
truncated: false,
});
const day = await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
expect(day.segments).toHaveLength(1);
expect(day.segments[0]?.points[0]).toEqual([52.0, 13.0]);
});
it('DAWARICH-TRACKS-059: a failing instance refuses with its reason, a refused key as 400 and anything else as 502', async () => {
const h = harness({ capabilities: { ...CAPABILITIES, tracks: false } });
h.listPoints.mockRejectedValueOnce(new DawarichError('server_error', 'Dawarich answered HTTP 500', 500));
const failed = (await h.service
.fetchDay(USER, '2026-05-01', CHOSEN_UTC)
.catch((err: unknown) => err)) as DomainError;
expect(failed.getStatus()).toBe(502);
expect(failed.toBody()).toEqual({ error: 'Dawarich answered HTTP 500', code: 'server_error' });
h.listPoints.mockRejectedValueOnce(new DawarichError('unauthorized', 'Dawarich rejected the API key', 401));
const refused = (await h.service
.fetchDay(USER, '2026-05-01', CHOSEN_UTC)
.catch((err: unknown) => err)) as DomainError;
expect(refused.getStatus()).toBe(400);
expect(refused.toBody()).toMatchObject({ code: 'unauthorized' });
});
it('DAWARICH-TRACKS-060: a tracks failure falls back to points instead of failing the day', async () => {
const h = harness({ capabilities: CAPABILITIES });
h.listTracks.mockRejectedValue(new DawarichError('not_found', 'no tracks endpoint', 404));
h.listPoints.mockResolvedValue({
points: [point(52.0, 13.0, '2026-05-01T10:00:00Z'), point(52.2, 13.2, '2026-05-01T10:10:00Z')],
truncated: true,
});
const day = await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
expect(day).toMatchObject({ sourceKind: 'points', truncated: true });
expect(day.segments).toHaveLength(1);
});
it('DAWARICH-TRACKS-061: reads past the cache, so what a journey keeps is what the instance says now', async () => {
const h = harness({ capabilities: { ...CAPABILITIES, tracks: false } });
await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
await h.service.fetchDay(USER, '2026-05-01', CHOSEN_UTC);
expect(h.listPoints).toHaveBeenCalledTimes(2);
});
});
@@ -15,6 +15,7 @@ import type {
DawarichVisitRaw,
} from '../../../src/nest/integrations/dawarich.client';
import {
RECORDING_GAP,
bucketPointsByDay,
bucketTracksByDay,
capPoints,
@@ -27,6 +28,7 @@ import {
normalizeVisit,
offsetMinutesOf,
simplify,
splitAtGaps,
splitWindow,
syncWindow,
toNumber,
@@ -800,6 +802,41 @@ describe('bucketPointsByDay', () => {
expect(line.at(-1)).toEqual([0, 2]);
});
it('DAWARICH-BUCKET-011: with gaps kept, a day becomes one piece per run and is never joined to the day before', () => {
const days = bucketPointsByDay(
[
point('2024-06-14T23:00:00Z', 9, 9),
point('2024-06-15T08:00:00Z', 10, 10),
point('2024-06-15T08:10:00Z', 10.001, 10.001),
point('2024-06-15T12:00:00Z', 11, 11),
point('2024-06-15T12:10:00Z', 11.001, 11.001),
],
0,
{ gaps: RECORDING_GAP },
);
// The lone point of the 14th is no line, so that day is not emitted.
expect(days.map((d) => d.date)).toEqual(['2024-06-15']);
expect(days[0]?.segments.map((s) => s.points[0])).toEqual([
[10, 10],
[11, 11],
]);
expect(days[0]?.segments[1]?.startedAt).toBe('2024-06-15T12:00:00.000Z');
});
it('DAWARICH-BUCKET-012: with gaps kept, a run that is one fix is left out rather than drawn as a dot', () => {
const days = bucketPointsByDay(
[
point('2024-06-15T08:00:00Z', 10, 10),
point('2024-06-15T12:00:00Z', 11, 11),
point('2024-06-15T12:10:00Z', 11.001, 11),
],
0,
{ gaps: RECORDING_GAP },
);
expect(days[0]?.segments).toHaveLength(1);
expect(days[0]?.segments[0]?.points[0]).toEqual([11, 11]);
});
it('DAWARICH-BUCKET-010: a recorded day carries no mode and no measured distance', () => {
const days = bucketPointsByDay([point('2024-06-15T10:00:00Z', 10, 10), point('2024-06-15T12:00:00Z', 10, 11)], 0);
expect(days[0]!.segments[0]!.mode).toBeNull();
@@ -1114,6 +1151,40 @@ describe('bucketTracksByDay', () => {
it('DAWARICH-TRACK-013: an empty feature list is an empty result', () => {
expect(bucketTracksByDay([])).toEqual([]);
});
it('DAWARICH-TRACK-016: a zone given cuts at its own midnight, not at the one the times carry', () => {
const late = track('2024-06-15T23:30:00+02:00', '2024-06-15T23:50:00+02:00', [
[10, 10],
[11, 11],
]);
expect(bucketTracksByDay([late]).map((d) => d.date)).toEqual(['2024-06-15']);
// 21:30 UTC is the next day in Tokyo.
expect(bucketTracksByDay([late], { offsetMinutes: 540 }).map((d) => d.date)).toEqual(['2024-06-16']);
});
});
// ── splitAtGaps ──────────────────────────────────────────────────────────────
describe('splitAtGaps', () => {
const at = (minute: number, lat: number, lng: number) => ({ lat, lng, ts: minute * 60 });
it('DAWARICH-GAP-001: a silence that ends elsewhere starts a new run', () => {
const runs = splitAtGaps(
[at(0, 52, 13), at(5, 52.001, 13), at(200, 52.05, 13.05), at(205, 52.051, 13.05)],
RECORDING_GAP,
);
expect(runs.map((run) => run.length)).toEqual([2, 2]);
});
it('DAWARICH-GAP-002: a long silence in the same spot and a quick long hop are both one movement', () => {
expect(splitAtGaps([at(0, 52, 13), at(120, 52.0001, 13.0001)], RECORDING_GAP)).toHaveLength(1);
// A train: kilometres between two fixes, minutes apart.
expect(splitAtGaps([at(0, 52, 13), at(5, 52.1, 13.1)], RECORDING_GAP)).toHaveLength(1);
});
it('DAWARICH-GAP-003: no points, no runs', () => {
expect(splitAtGaps([], RECORDING_GAP)).toEqual([]);
});
});
// ── countPoints ──────────────────────────────────────────────────────────────
@@ -0,0 +1,93 @@
/**
* JourneyRecordingsController (JRN-01): the routes of the recorded days a
* journey keeps, their guards, the date check it makes before the service is
* asked, and what it hands the service and answers.
*/
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 { JourneyRecordingsController } from '../../../src/nest/journey-recordings/journey-recordings.controller';
import type { JourneyRecordingsService } from '../../../src/nest/journey-recordings/journey-recordings.service';
import type { User } from '../../../src/types';
import { HttpException, 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;
const HASH = 'f'.repeat(64);
function controllerWith() {
const service = {
list: vi.fn(async () => []),
preview: vi.fn(async () => ({ date: '2026-05-14' })),
save: vi.fn(async () => ({ outcome: 'created' })),
remove: vi.fn(async () => undefined),
};
return {
service,
controller: new JourneyRecordingsController(service as unknown as JourneyRecordingsService),
};
}
describe('JourneyRecordingsController', () => {
it('JRNREC-CTL-001: sits behind the Journey addon before auth, with the preview and the removal answering 200', () => {
expect(Reflect.getMetadata(PATH_METADATA, JourneyRecordingsController)).toBe('api/journeys/:id/recordings');
expect(Reflect.getMetadata(GUARDS_METADATA, JourneyRecordingsController)).toEqual([AddonGuard, JwtAuthGuard]);
expect(Reflect.getMetadata(REQUIRE_ADDON, JourneyRecordingsController)).toEqual({
addonId: 'journey',
label: 'Journey',
});
const routes = [
['list', RequestMethod.GET, '/', undefined],
['preview', RequestMethod.POST, 'preview', 200],
['save', RequestMethod.PUT, ':date', undefined],
['remove', RequestMethod.DELETE, ':date', 200],
] as const;
for (const [handler, method, path, code] of routes) {
const fn = JourneyRecordingsController.prototype[handler];
expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(method);
expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(path);
expect(Reflect.getMetadata(HTTP_CODE_METADATA, fn)).toBe(code);
}
});
it('JRNREC-CTL-002: hands the caller, the journey, the day, the body and the socket id to the service', async () => {
const { service, controller } = controllerWith();
expect(await controller.list(user, '9')).toEqual({ days: [] });
expect(service.list).toHaveBeenCalledExactlyOnceWith(4, 9);
const preview = { date: '2026-05-14', utcOffsetMinutes: 120, useSourceOffset: true };
expect(await controller.preview(user, '9', preview)).toEqual({ date: '2026-05-14' });
expect(service.preview).toHaveBeenCalledExactlyOnceWith(4, 9, preview);
const save = { utcOffsetMinutes: 120, expectedHash: HASH, replace: true };
expect(await controller.save(user, '9', '2026-05-14', save, 'sock-1')).toEqual({ outcome: 'created' });
expect(service.save).toHaveBeenCalledExactlyOnceWith(4, 9, '2026-05-14', save, 'sock-1');
expect(await controller.remove(user, '9', '2026-05-14', 'sock-1')).toEqual({ success: true });
expect(service.remove).toHaveBeenCalledExactlyOnceWith(4, 9, '2026-05-14', 'sock-1');
});
it('JRNREC-CTL-003: a day that is no calendar day is a 400 before the service is asked', async () => {
const { service, controller } = controllerWith();
const refusals = await Promise.all(
['2026-02-30', '14.05.2026', 'today'].map((date) =>
controller.remove(user, '9', date).catch((err: unknown) => err),
),
);
for (const err of refusals) {
expect(err).toBeInstanceOf(HttpException);
expect((err as HttpException).getStatus()).toBe(400);
expect((err as HttpException).getResponse()).toEqual({ error: 'Invalid date' });
}
await expect(
controller.save(user, '9', 'nope', { utcOffsetMinutes: 0, expectedHash: HASH }),
).rejects.toBeInstanceOf(HttpException);
expect(service.remove).not.toHaveBeenCalled();
expect(service.save).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,179 @@
/**
* JourneyRecordingsMcp (JRN-01): the recorded days a journey keeps over MCP,
* on the same service and journey access as REST. The suite takes its subject
* from the container over a snapshot test db; only the read from Dawarich is
* replaced. A tool answers what a day covers and never its geometry.
*/
import { JourneyRecordedDays } from '../../../src/db/entities/JourneyRecordedDays.entity';
import type { McpContext } from '../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { DawarichTracksService, type RecordedDayFetch } from '../../../src/nest/integrations/dawarich-tracks.service';
import { JourneyRecordingsMcp } from '../../../src/nest/journey-recordings/journey-recordings.mcp';
import { JourneyRecordingsModule } from '../../../src/nest/journey-recordings/journey-recordings.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../helpers/factories/journeys';
import { countRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
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();
const fetchDay = vi.fn<(...args: unknown[]) => Promise<RecordedDayFetch>>();
let t: TestModule;
let orm: TestOrm;
let mcp: JourneyRecordingsMcp;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [JourneyRecordingsModule],
overrides: [{ provide: DawarichTracksService, useValue: { fetchDay } }],
});
mcp = t.get(JourneyRecordingsMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
fetchDay.mockReset();
await setAddonEnabled(orm, 'journey', true);
await setAddonEnabled(orm, 'dawarich', true);
});
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);
}
const DAY: RecordedDayFetch = {
segments: [
{
points: [
[45.434, 12.3388],
[45.4364, 12.3218],
],
mode: 'walking',
startedAt: '2026-05-14T09:00:00+02:00',
endedAt: '2026-05-14T09:40:00+02:00',
distanceMeters: 1500,
},
],
sourceKind: 'tracks',
utcOffsetMinutes: 120,
offsetSource: 'source',
sourceOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
fetchedAt: '2026-05-15T07:00:00.000Z',
truncated: false,
};
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');
return { owner, viewer, journey };
}
describe('JourneyRecordingsMcp', () => {
it('JRNREC-MCP-001: previews, keeps, lists and drops a day, answering without geometry', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(DAY);
const preview = read(
await mcp.previewRecordedDay(
{ journeyId: f.journey.id, date: '2026-05-14', utcOffsetMinutes: 0, useSourceOffset: true },
ctx(f.owner.id),
),
);
expect(preview).toMatchObject({
journey: { id: f.journey.id, title: 'Venice' },
utcOffsetMinutes: 120,
stats: { distanceMeters: 1500, segmentCount: 1 },
stored: null,
audience: 1,
});
expect(preview.segments).toBeUndefined();
const saved = read(
await mcp.saveRecordedDay(
{ journeyId: f.journey.id, date: '2026-05-14', utcOffsetMinutes: 120, expectedHash: preview.contentHash },
ctx(f.owner.id),
),
);
expect(saved.outcome).toBe('created');
expect(saved.day).toMatchObject({ date: '2026-05-14', sourceKind: 'tracks' });
expect(saved.day.segments).toBeUndefined();
const listed = read(await mcp.listRecordedDays({ journeyId: f.journey.id }, ctx(f.viewer.id)));
expect(listed.days).toHaveLength(1);
expect(listed.days[0].segments).toBeUndefined();
const again = read(
await mcp.previewRecordedDay(
{ journeyId: f.journey.id, date: '2026-05-14', utcOffsetMinutes: 0, useSourceOffset: true },
ctx(f.owner.id),
),
);
expect(again).toMatchObject({ sameAsStored: true, stored: { date: '2026-05-14' } });
expect(again.stored.segments).toBeUndefined();
expect(read(await mcp.deleteRecordedDay({ journeyId: f.journey.id, date: '2026-05-14' }, ctx(f.owner.id)))).toEqual(
{ success: true },
);
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
it('JRNREC-MCP-002: refuses what REST refuses: a viewer keeps nothing, a stranger reads nothing', async () => {
const f = await fixture();
const { user: stranger } = await makeUser(orm);
fetchDay.mockResolvedValue(DAY);
await expect(
mcp.saveRecordedDay(
{ journeyId: f.journey.id, date: '2026-05-14', utcOffsetMinutes: 120, expectedHash: 'a'.repeat(64) },
ctx(f.viewer.id),
),
).rejects.toThrow('Not allowed');
await expect(mcp.listRecordedDays({ journeyId: f.journey.id }, ctx(stranger.id))).rejects.toThrow(
'Journey not found',
);
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
it('JRNREC-MCP-003: reading and dropping need the Journey addon, previewing and keeping need Dawarich too', async () => {
const options = (name: string) => {
const entry = getEntry(JourneyRecordingsMcp 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 = ['listRecordedDays', 'deleteRecordedDay', 'previewRecordedDay', 'saveRecordedDay'];
const gates = () => Promise.all(ALL.map((name) => options(name).when?.(ctx(1), mcp)));
expect(await gates()).toEqual([true, true, true, true]);
enabled.mockImplementation(async (id: string) => id !== 'dawarich');
expect(await gates()).toEqual([true, true, false, false]);
enabled.mockImplementation(async (id: string) => id !== 'journey');
expect(await gates()).toEqual([false, false, false, false]);
expect(options('listRecordedDays').access).toEqual({ group: 'journey', mode: 'read' });
expect(options('previewRecordedDay').access).toEqual({ group: 'journey', mode: 'read' });
expect(options('saveRecordedDay').access).toEqual({ group: 'journey', mode: 'write' });
expect(options('deleteRecordedDay').access).toEqual({ group: 'journey', mode: 'write' });
});
});
@@ -0,0 +1,352 @@
/**
* JourneyRecordingsService (JRN-01): taking a day's recorded route over into a
* journey. The suite takes the service from its module over a snapshot test
* db; only the read from Dawarich is replaced, so the journey access, the kept
* rows and the broadcasts are the real ones.
*
* What it pins: a preview writes nothing and says what would be kept, for
* which journey and day and who would see it; a save keeps exactly the day
* that was previewed, once, replaces a different version only when asked and
* never touches an entry; a failed read keeps the version the journey had;
* reading and removing kept days need no Dawarich at all.
*/
import { JourneyEntries } from '../../../src/db/entities/JourneyEntries.entity';
import { JourneyRecordedDays } from '../../../src/db/entities/JourneyRecordedDays.entity';
import { DomainError } from '../../../src/nest/common/domain-error';
import { DawarichTracksService, type RecordedDayFetch } from '../../../src/nest/integrations/dawarich-tracks.service';
import { JourneyRecordingsModule } from '../../../src/nest/journey-recordings/journey-recordings.module';
import { JourneyRecordingsService } from '../../../src/nest/journey-recordings/journey-recordings.service';
import { JourneyRecordedDaysService } from '../../../src/nest/journey/journey-recorded-days.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../../helpers/factories/journeys';
import { countRows, findRow } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
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();
const fetchDay = vi.fn<(...args: unknown[]) => Promise<RecordedDayFetch>>();
let t: TestModule;
let orm: TestOrm;
let svc: JourneyRecordingsService;
let kept: JourneyRecordedDaysService;
beforeAll(async () => {
t = await createTestModule({
db,
imports: [JourneyRecordingsModule],
overrides: [{ provide: DawarichTracksService, useValue: { fetchDay } }],
});
svc = t.get(JourneyRecordingsService);
kept = t.get(JourneyRecordedDaysService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
fetchDay.mockReset();
t.realtime.reset();
await setAddonEnabled(orm, 'journey', true);
await setAddonEnabled(orm, 'dawarich', true);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const WALK = {
points: [
[45.434, 12.3388],
[45.4364, 12.3218],
] as Array<[number, number]>,
mode: 'walking',
startedAt: '2026-05-14T09:00:00+02:00',
endedAt: '2026-05-14T09:40:00+02:00',
distanceMeters: 1500,
};
function recorded(over: Partial<RecordedDayFetch> = {}): RecordedDayFetch {
return {
segments: [WALK],
sourceKind: 'tracks',
utcOffsetMinutes: 120,
offsetSource: 'source',
sourceOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
fetchedAt: '2026-05-15T07:00:00.000Z',
truncated: false,
...over,
};
}
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 };
}
const PREVIEW = { date: '2026-05-14', utcOffsetMinutes: 0, useSourceOffset: true };
async function refusal(promise: Promise<unknown>): Promise<{ status: number; body: Record<string, unknown> }> {
const err = await promise.then(
() => null,
(e: unknown) => e,
);
expect(err).toBeInstanceOf(DomainError);
return { status: (err as DomainError).getStatus(), body: (err as DomainError).toBody() };
}
describe('JourneyRecordingsService.preview', () => {
it('JRNREC-SVC-001: says which journey, day and recording would be kept, and who would see it, keeping nothing', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const preview = await svc.preview(f.owner.id, f.journey.id, PREVIEW);
expect(fetchDay).toHaveBeenCalledWith(f.owner.id, '2026-05-14', { offsetMinutes: 0, useSourceOffset: true });
expect(preview).toMatchObject({
journey: { id: f.journey.id, title: 'Venice' },
date: '2026-05-14',
utcOffsetMinutes: 120,
offsetSource: 'source',
sourceOffsetMinutes: 120,
sourceKind: 'tracks',
stats: { distanceMeters: 1500, segmentCount: 1, gapCount: 0, modes: ['walking'] },
provisional: false,
stored: null,
sameAsStored: false,
audience: 2,
});
expect(preview.contentHash).toMatch(/^[0-9a-f]{64}$/);
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
it('JRNREC-SVC-002: a day with nothing recorded has no hash to keep, and a running day is provisional', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded({ segments: [], fetchedAt: '2026-05-14T12:00:00.000Z' }));
const preview = await svc.preview(f.owner.id, f.journey.id, PREVIEW);
expect(preview).toMatchObject({ contentHash: null, provisional: true, stats: { segmentCount: 0 } });
});
it('JRNREC-SVC-003: refuses a stranger with 404, a viewer with 403 and a switched-off Dawarich, before asking it', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
expect(await refusal(svc.preview(f.outsider.id, f.journey.id, PREVIEW))).toEqual({
status: 404,
body: { error: 'Journey not found' },
});
expect(await refusal(svc.preview(f.viewer.id, f.journey.id, PREVIEW))).toEqual({
status: 403,
body: { error: 'Not allowed' },
});
await setAddonEnabled(orm, 'dawarich', false);
expect(await refusal(svc.preview(f.owner.id, f.journey.id, PREVIEW))).toEqual({
status: 404,
body: { error: 'Dawarich is not enabled', code: 'addon_disabled' },
});
expect(fetchDay).not.toHaveBeenCalled();
});
it('JRNREC-SVC-004: shows the version the journey keeps and whether the live one is the same', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const first = await svc.preview(f.owner.id, f.journey.id, PREVIEW);
await svc.save(f.owner.id, f.journey.id, '2026-05-14', {
utcOffsetMinutes: 120,
expectedHash: String(first.contentHash),
});
const same = await svc.preview(f.editor.id, f.journey.id, PREVIEW);
expect(same).toMatchObject({ sameAsStored: true, stored: { importedBy: { username: 'marta' } } });
fetchDay.mockResolvedValue(recorded({ segments: [WALK, { ...WALK, startedAt: '2026-05-14T15:00:00+02:00' }] }));
const grown = await svc.preview(f.editor.id, f.journey.id, PREVIEW);
expect(grown.sameAsStored).toBe(false);
expect(grown.stored?.stats.segmentCount).toBe(1);
});
});
describe('JourneyRecordingsService.save', () => {
async function previewed(userId: number, journeyId: number) {
const preview = await svc.preview(userId, journeyId, PREVIEW);
return { utcOffsetMinutes: preview.utcOffsetMinutes, expectedHash: String(preview.contentHash) };
}
it('JRNREC-SVC-005: keeps the previewed day in the zone it was cut in and tells everyone on the journey', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const body = await previewed(f.editor.id, f.journey.id);
const result = await svc.save(f.editor.id, f.journey.id, '2026-05-14', body, 'sock-1');
expect(fetchDay).toHaveBeenLastCalledWith(f.editor.id, '2026-05-14', {
offsetMinutes: 120,
useSourceOffset: false,
});
expect(result.outcome).toBe('created');
expect(result.day).toMatchObject({
date: '2026-05-14',
source: 'dawarich',
sourceKind: 'tracks',
utcOffsetMinutes: 120,
window: { from: '2026-05-13T22:00:00.000Z', to: '2026-05-14T22:00:00.000Z' },
segments: [WALK],
truncated: false,
provisional: false,
importedBy: { id: f.editor.id, username: 'jonas' },
});
const recipients = t.realtime.broadcastToUserMock.mock.calls.map(([userId]) => userId).sort();
expect(recipients).toEqual([f.owner.id, f.editor.id, f.viewer.id].sort());
expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(
f.owner.id,
{ type: 'journey:recording:updated', journeyId: f.journey.id, date: '2026-05-14' },
'sock-1',
);
});
it('JRNREC-SVC-006: the same day taken over again keeps one version and announces nothing', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const body = await previewed(f.owner.id, f.journey.id);
await svc.save(f.owner.id, f.journey.id, '2026-05-14', body);
t.realtime.reset();
const again = await svc.save(f.owner.id, f.journey.id, '2026-05-14', body);
expect(again.outcome).toBe('unchanged');
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(1);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('JRNREC-SVC-007: a different version replaces the kept one only when asked, and no entry is touched', async () => {
const f = await fixture();
const entry = await makeJourneyEntry(orm, f.journey.id, f.owner.id, {
entry_date: '2026-05-14',
title: 'Rialto',
story: 'Coffee by the bridge',
});
fetchDay.mockResolvedValue(recorded());
await svc.save(f.owner.id, f.journey.id, '2026-05-14', await previewed(f.owner.id, f.journey.id));
fetchDay.mockResolvedValue(recorded({ segments: [WALK, { ...WALK, startedAt: '2026-05-14T15:00:00+02:00' }] }));
const body = await previewed(f.owner.id, f.journey.id);
expect(await refusal(svc.save(f.owner.id, f.journey.id, '2026-05-14', body))).toEqual({
status: 409,
body: { error: 'The journey already keeps another recording of that day', code: 'recording_exists' },
});
expect((await kept.find(f.journey.id, '2026-05-14'))?.stats.segmentCount).toBe(1);
const replaced = await svc.save(f.owner.id, f.journey.id, '2026-05-14', { ...body, replace: true });
expect(replaced.outcome).toBe('replaced');
expect(replaced.day.stats.segmentCount).toBe(2);
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(1);
expect(await findRow(orm, JourneyEntries, { id: entry.id })).toMatchObject({
title: 'Rialto',
story: 'Coffee by the bridge',
});
});
it('JRNREC-SVC-008: a recording that changed since the preview is not kept, and the kept version stays', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const body = await previewed(f.owner.id, f.journey.id);
await svc.save(f.owner.id, f.journey.id, '2026-05-14', body);
fetchDay.mockResolvedValue(recorded({ segments: [{ ...WALK, distanceMeters: 1800 }] }));
expect(await refusal(svc.save(f.owner.id, f.journey.id, '2026-05-14', { ...body, replace: true }))).toEqual({
status: 409,
body: { error: 'The recording changed since the preview', code: 'recording_changed' },
});
expect((await kept.find(f.journey.id, '2026-05-14'))?.stats.distanceMeters).toBe(1500);
});
it('JRNREC-SVC-009: a failed read throws before anything is written, so the kept version stays as it was', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded());
const body = await previewed(f.owner.id, f.journey.id);
await svc.save(f.owner.id, f.journey.id, '2026-05-14', body);
t.realtime.reset();
fetchDay.mockRejectedValue(
new DomainError(502, 'Dawarich answered HTTP 500', { details: { code: 'server_error' } }),
);
expect(await refusal(svc.save(f.owner.id, f.journey.id, '2026-05-14', { ...body, replace: true }))).toEqual({
status: 502,
body: { error: 'Dawarich answered HTTP 500', code: 'server_error' },
});
expect((await kept.find(f.journey.id, '2026-05-14'))?.contentHash).toBe(body.expectedHash);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('JRNREC-SVC-010: a day with nothing recorded is refused, and a viewer may not keep one', async () => {
const f = await fixture();
fetchDay.mockResolvedValue(recorded({ segments: [] }));
const body = { utcOffsetMinutes: 120, expectedHash: 'a'.repeat(64) };
expect(await refusal(svc.save(f.owner.id, f.journey.id, '2026-05-14', body))).toEqual({
status: 422,
body: { error: 'Dawarich recorded nothing on that day', code: 'recording_empty' },
});
expect((await refusal(svc.save(f.viewer.id, f.journey.id, '2026-05-14', body))).status).toBe(403);
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
});
});
describe('JourneyRecordingsService.list and remove', () => {
async function keptDay(f: Awaited<ReturnType<typeof fixture>>) {
fetchDay.mockResolvedValue(recorded());
const preview = await svc.preview(f.owner.id, f.journey.id, PREVIEW);
await svc.save(f.owner.id, f.journey.id, '2026-05-14', {
utcOffsetMinutes: preview.utcOffsetMinutes,
expectedHash: String(preview.contentHash),
});
t.realtime.reset();
}
it('JRNREC-SVC-011: anyone who can open the journey reads its kept days, also with Dawarich switched off', async () => {
const f = await fixture();
await keptDay(f);
await setAddonEnabled(orm, 'dawarich', false);
fetchDay.mockReset();
const days = await svc.list(f.viewer.id, f.journey.id);
expect(days.map((day) => day.date)).toEqual(['2026-05-14']);
expect(days[0]?.segments).toEqual([WALK]);
expect(fetchDay).not.toHaveBeenCalled();
expect((await refusal(svc.list(f.outsider.id, f.journey.id))).status).toBe(404);
});
it('JRNREC-SVC-012: an editor removes a kept day without Dawarich and everyone is told; a missing one is a 404', async () => {
const f = await fixture();
await keptDay(f);
await setAddonEnabled(orm, 'dawarich', false);
expect((await refusal(svc.remove(f.viewer.id, f.journey.id, '2026-05-14'))).status).toBe(403);
await svc.remove(f.editor.id, f.journey.id, '2026-05-14', 'sock-2');
expect(await countRows(orm, JourneyRecordedDays, {})).toBe(0);
expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(
f.viewer.id,
{ type: 'journey:recording:updated', journeyId: f.journey.id, date: '2026-05-14' },
'sock-2',
);
expect(await refusal(svc.remove(f.editor.id, f.journey.id, '2026-05-14'))).toEqual({
status: 404,
body: { error: 'No recording kept for that day' },
});
});
});
+3
View File
@@ -126,6 +126,9 @@ export default defineConfig({
'src/nest/help/**/*.ts': { statements: 81, branches: 70, functions: 99, lines: 86 },
'src/nest/integrations/**/*.ts': { statements: 78, branches: 68, functions: 78, lines: 80 },
'src/nest/journey/**/*.ts': { statements: 91, branches: 84, functions: 88, lines: 93 },
// New domain in this change (JRN-01), unmeasured: pinned at the 80 floor
// like ferratas until the first full run regenerates it.
'src/nest/journey-recordings/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 },
'src/nest/llm-parse/**/*.ts': { statements: 91, branches: 85, functions: 85, lines: 94 },
'src/nest/managed/**/*.ts': { statements: 100, branches: 100, functions: 100, lines: 100 },
'src/nest/maps/**/*.ts': { statements: 93, branches: 86, functions: 97, lines: 96 },