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
@@ -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' },
});
});
});