fix(atlas): count shared days for every member, keep routes and multi-day tours honest (STA-02)

A day of a tour that names nobody now counts for every member of the trip,
not only for its owner. In the planner an empty participant list means
everyone, and a full member list is stored back as empty, so members got
nothing for most shared tours. Only a day that names participants without
the user stays theirs. The tours of a shared trip on no day or only on
undated days are now named as not counting for members as well.

A whole route a multi-day tour's stages were planned from is no longer
dropped on the server as soon as any stage has a day. Each entry carries
derived_from_place_id and the shared summary leaves the route out only
while one of its stages is done, counted and in the period and type. A
route walked last year now still counts when a stage of it is planned for
next month or was left out because it fell through, in the Atlas and over
MCP alike.

A tour on several days is dated on the last of them, as is a recording on
no day, so it no longer counts while it is still under way.

The info text, the get_tour_activity_stats description and the wiki say so.
This commit is contained in:
Maurice
2026-10-20 13:51:46 +02:00
parent bde2ad2ca8
commit acc294dd8e
47 changed files with 233 additions and 123 deletions
@@ -36,9 +36,9 @@ export interface TourActivityRow extends TourActivityRefRow {
/**
* STA-02: one tour of a trip the user can open, once per day assignment it has
* (once with `assignment_id` NULL when it is on no day), with what the activity
* sums need: its plan's measures, the day's date, the trip's owner, and who the
* execution names as taking part (`participant_count`, and `joined` 1 when the
* user is one of them).
* sums need: its plan's measures, the import it was planned from, the day's
* date, and who the execution names as taking part (`participant_count`, and
* `joined` 1 when the user is one of them).
*/
export interface TourStatsExecutionRow {
place_id: number;
@@ -50,7 +50,6 @@ export interface TourStatsExecutionRow {
derived_from_place_id: number | null;
trip_id: number;
trip_title: string;
trip_owner_id: number;
assignment_id: number | null;
date: string | null;
participant_count: number;
@@ -191,7 +190,6 @@ export class TourActivitiesRepository extends TrekRepository<TourActivities> {
't.derived_from_place_id as derived_from_place_id',
'tr.id as trip_id',
'tr.title as trip_title',
'tr.user_id as trip_owner_id',
'da.id as assignment_id',
'd.date as date',
eb
@@ -14,7 +14,7 @@ import { tourActivityStatsResponseSchema } from '@trek/shared';
* STA-02 /api/tours/activity-stats: the user's own tour activities across
* their trips, for the Atlas, and leaving one out of them. Not trip-scoped,
* so there is no TripAccessGuard; the service bounds every answer by the
* user's own trips. Leaving a tour out changes only the user's own sums, so it
* trips the user owns or is a member of. Leaving a tour out changes only the user's own sums, so it
* asks for no trip permission beyond being able to open the trip.
*/
@Controller('api/tours/activity-stats')
@@ -3,7 +3,9 @@
* of the trips the user can open, once per day it is on, and the recordings
* assigned to them; what comes out is the list of the user's done (or still
* upcoming) tours the shared summary adds up, see `tour-activity-stats.schema`
* in @trek/shared for the rules this follows.
* in @trek/shared for the rules this follows. Whether an entry is done, and
* which whole route its counted stages stand in for, is up to that summary:
* both depend on the reader's today.
*/
import type { TourStatsExecutionRow, TourStatsTrackRow } from '../../db/repositories/TourActivities.repository';
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
@@ -22,7 +24,6 @@ interface DatedExecution {
}
interface ActivityStatsInput {
userId: number;
executions: readonly TourStatsExecutionRow[];
tracks: readonly TourStatsTrackRow[];
/** The tours the user left out of their own sums. */
@@ -31,12 +32,12 @@ interface ActivityStatsInput {
/**
* Whether an execution is the user's own: it names the user among those taking
* part, or names nobody on a trip that is the user's. Being able to open
* someone else's trip alone makes none of its tours the user's.
* part, or names nobody, which in the planner means everyone of the trip. The
* rows only hold trips the user owns or is a member of, so a day that names
* participants without the user is the only one that is not theirs.
*/
export function isOwnExecution(row: TourStatsExecutionRow, userId: number): boolean {
if (row.joined === 1) return true;
return row.participant_count === 0 && row.trip_owner_id === userId;
export function isOwnExecution(row: TourStatsExecutionRow): boolean {
return row.joined === 1 || row.participant_count === 0;
}
/** A trip day's date as a calendar day, null when the day has none. */
@@ -56,8 +57,8 @@ function groupByTour(rows: readonly TourStatsExecutionRow[]): TourOfStats[] {
}
/** The user's executions of a tour, and of those the ones on a dated day, the earliest first. */
function ownExecutions(tour: TourOfStats, userId: number): { own: number; dated: DatedExecution[] } {
const own = tour.executions.filter((row) => isOwnExecution(row, userId));
function ownExecutions(tour: TourOfStats): { own: number; dated: DatedExecution[] } {
const own = tour.executions.filter(isOwnExecution);
const dated: DatedExecution[] = [];
for (const row of own) {
const date = calendarDay(row.date);
@@ -84,21 +85,25 @@ function baseEntry(tour: TourOfStats, excluded: ReadonlySet<number>) {
name: row.name,
tour_type: row.tour_type as TourTypeKey,
trip: { id: row.trip_id, title: row.trip_title },
derived_from_place_id: row.derived_from_place_id,
excluded: excluded.has(row.place_id),
};
}
/** The plan standing in for the tour: once, on the first of its days, however many there are. */
/**
* The plan standing in for the tour: once, however many days it is on, on the
* last of them, so a tour still under way does not count before it is done.
*/
function planEntry(
tour: TourOfStats,
first: DatedExecution,
last: DatedExecution,
dayCount: number,
excluded: ReadonlySet<number>,
): TourActivityStatsEntry {
const { row } = tour;
return {
...baseEntry(tour, excluded),
date: first.date,
date: last.date,
basis: 'plan',
track: null,
day_count: dayCount,
@@ -129,55 +134,58 @@ function trackEntry(
/**
* A tour's entries: one per recording of one of the user's executions (a
* recording on no day counts with the first of them), or else the plan once.
* A recording of someone else's execution is theirs, not the user's.
* recording on no day stands for the whole tour, so it counts with the last of
* them), or else the plan once. A recording of someone else's execution is
* theirs, not the user's.
*/
function entriesOfTour(
tour: TourOfStats,
[first, ...rest]: [DatedExecution, ...DatedExecution[]],
dated: readonly DatedExecution[],
last: DatedExecution,
tracks: readonly TourStatsTrackRow[],
excluded: ReadonlySet<number>,
): TourActivityStatsEntry[] {
const dateOf = new Map([first, ...rest].map((execution) => [execution.assignmentId, execution.date]));
const dateOf = new Map(dated.map((execution) => [execution.assignmentId, execution.date]));
const recorded = tracks
.filter((track) => track.place_id === tour.row.place_id)
.map((track) => ({ track, date: track.assignment_id === null ? first.date : dateOf.get(track.assignment_id) }))
.map((track) => ({ track, date: track.assignment_id === null ? last.date : dateOf.get(track.assignment_id) }))
.filter((item): item is { track: TourStatsTrackRow; date: string } => item.date !== undefined);
if (recorded.length === 0) return [planEntry(tour, first, rest.length + 1, excluded)];
if (recorded.length === 0) return [planEntry(tour, last, dated.length, excluded)];
return recorded.map(({ track, date }) => trackEntry(tour, track, date, excluded));
}
/** What became of one tour: its entries, or why a tour of the user's own trip cannot count. */
/** What became of one tour: its entries, or why a tour of the user's cannot count. */
type TourOutcome = TourActivityStatsEntry[] | 'unassigned' | 'undated' | null;
function outcomeOf(tour: TourOfStats, input: ActivityStatsInput): TourOutcome {
const { own, dated } = ownExecutions(tour, input.userId);
const [first, ...rest] = dated;
if (first) return entriesOfTour(tour, [first, ...rest], input.tracks, input.excluded);
if (tour.row.trip_owner_id !== input.userId) return null;
const { own, dated } = ownExecutions(tour);
const last = dated.at(-1);
if (last) return entriesOfTour(tour, dated, last, input.tracks, input.excluded);
if (tour.executions.length === 0) return 'unassigned';
return own > 0 ? 'undated' : null;
}
/**
* The user's activity entries and what of their own trips cannot count. A
* recording is never a tour of its own here, and an import other tours were
* planned from (a whole route and its stages) is left out while one of those
* tours counts, so nothing is added up twice.
* The user's activity entries and what of their trips cannot count. A
* recording is never a tour of its own here. A whole route other tours were
* planned from keeps its entries and each stage names it in
* `derived_from_place_id`: the shared summary leaves the route out only while
* one of its stages counts, which takes the reader's today. A route whose
* stages are on the user's days is not named as uncounted either, since they
* stand in for it.
*/
export function buildActivityStats(input: ActivityStatsInput): TourActivityStatsResponse {
const recordings = new Set(input.tracks.map((track) => track.track_place_id));
const tours = groupByTour(input.executions).filter((tour) => !recordings.has(tour.row.place_id));
const outcomes = tours.map((tour) => ({ tour, outcome: outcomeOf(tour, input) }));
const stagesCounted = new Set(
const routesOfPlannedStages = new Set(
outcomes.filter(({ outcome }) => Array.isArray(outcome)).map(({ tour }) => tour.row.derived_from_place_id),
);
const uncounted = { unassigned: 0, undated: 0 };
const entries: TourActivityStatsEntry[] = [];
for (const { tour, outcome } of outcomes) {
if (outcome === null || stagesCounted.has(tour.row.place_id)) continue;
if (Array.isArray(outcome)) entries.push(...outcome);
else uncounted[outcome] += 1;
else if (outcome !== null && !routesOfPlannedStages.has(tour.row.place_id)) uncounted[outcome] += 1;
}
entries.sort((a, b) => b.date.localeCompare(a.date) || a.name.localeCompare(b.name) || a.place_id - b.place_id);
return { entries, uncounted };
@@ -59,7 +59,7 @@ export class TourActivityStatsMcp {
@Tool({
name: 'get_tour_activity_stats',
description:
'The tours the user has done, summed: how many, distance in km, ascent and descent in metres, as a whole and by type, for a period (from and to, YYYY-MM-DD, both included) and one type, or all of them. A tour counts once the day it is on is over (today is UTC here), and only where the user took part: a day of the tour names the user among its participants, or names none on a trip the user owns. Merely being able to open a trip of somebody else counts nothing. basis "plan" means the values come from the planning of the trip, not from a measurement, and must be said so; basis "track" means a recorded track linked to the tour replaced them. A tour on several days counts once; a paddle tour sums no heights; null means unknown, never zero. Tours the user left out (excluded true) are listed but not summed. uncounted names the tours of trips the user owns that are on no day or only on days without a date.',
'The tours the user has done, summed: how many, distance in km, ascent and descent in metres, as a whole and by type, for a period (from and to, YYYY-MM-DD, both included) and one type, or all of them. A tour counts once the last day it is on is over (today is UTC here), and only where the user takes part: a day of the tour names the user among its participants, or names none, which means everyone of the trip. A day naming only others is theirs. basis "plan" means the values come from the planning of the trip, not from a measurement, and must be said so; basis "track" means a recorded track linked to the tour replaced them. A tour on several days counts once; a whole route stays out while a stage planned from it (derived_from_place_id) counts; a paddle tour sums no heights; null means unknown, never zero. Tours the user left out (excluded true) are listed but not summed. uncounted names the tours of the user's trips that are on no day or only on the user's days without a date.',
inputSchema: { from: query.from, to: query.to, type: query.type },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -34,7 +34,7 @@ export class TourActivityStatsService {
this.activitiesRepo.listTracksForStats(tripIds),
this.exclusionsRepo.listPlaceIds(userId),
]);
return buildActivityStats({ userId, executions, tracks, excluded: new Set(excluded) });
return buildActivityStats({ executions, tracks, excluded: new Set(excluded) });
}
/**
@@ -2,7 +2,8 @@
* STA-02 e2e: the user's own tour activities for the Atlas, through the real
* JwtAuthGuard and AddonGuard against a real migrated temp SQLite db. Tours
* are created through the tours API and put on dated days; whose they are
* follows the day's participants and the trip's owner, never mere access.
* follows the day's participants as the planner reads them: a day naming
* nobody is everyone's in the trip, a day naming people is only theirs.
*
* Fixtures: user 1 owns trip 5 (two dated days, one without a date), user 2 is
* a member, user 3 has no access.
@@ -163,15 +164,21 @@ describe('Tour activity stats e2e (STA-02)', () => {
}),
]);
expect(res.body.uncounted).toEqual({ unassigned: 1, undated: 1 });
// The days name nobody, so they are the member's as much as the owner's.
const member = await request(server).get(STATS).set(as(MEMBER));
expect(member.body).toEqual(res.body);
});
it('STA2-E2E-002: a member counts only the days naming them; an outsider gets nothing', async () => {
it('STA2-E2E-002: a day naming people counts only for them, one naming nobody for all; no outsider', async () => {
const ridge = await tourOnDay('Ridge', 3);
const lake = await tourOnDay('Lake', 4);
await insertRow(orm, AssignmentParticipants, { assignment: lake.assignmentId, user: MEMBER });
const member = await request(server).get(STATS).set(as(MEMBER));
expect(member.body.entries.map((entry: { place_id: number }) => entry.place_id)).toEqual([lake.placeId]);
expect(member.body.entries.map((entry: { place_id: number }) => entry.place_id)).toEqual([
lake.placeId,
ridge.placeId,
]);
expect(member.body.uncounted).toEqual({ unassigned: 0, undated: 0 });
// The owner is not on Lake's day any more, only on Ridge's.
const owner = await request(server).get(STATS).set(as(OWNER));
@@ -213,4 +220,13 @@ describe('Tour activity stats e2e (STA-02)', () => {
expect(off.status).toBe(404);
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
});
it('STA2-E2E-005: a tour on two days counts once, dated on the last of them', async () => {
const ridge = await tourOnDay('Ridge', 3);
await makeDayAssignment(orm, 4, ridge.placeId);
const res = await request(server).get(STATS).set(as(OWNER));
expect(res.body.entries).toEqual([
expect.objectContaining({ place_id: ridge.placeId, date: '2026-07-03', day_count: 2 }),
]);
});
});
@@ -84,7 +84,6 @@ describe('TourActivitiesRepository stats reads (STA-02)', () => {
derived_from_place_id: null,
trip_id: trip.id,
trip_title: 'Alps',
trip_owner_id: user.id,
participant_count: 1,
joined: 0,
});
@@ -7,9 +7,6 @@ import { buildActivityStats, isOwnExecution } from '../../../src/nest/tours/tour
import { describe, expect, it } from 'vitest';
const ME = 1;
const FRIEND = 2;
function row(overrides: Partial<TourStatsExecutionRow> = {}): TourStatsExecutionRow {
return {
place_id: 10,
@@ -21,7 +18,6 @@ function row(overrides: Partial<TourStatsExecutionRow> = {}): TourStatsExecution
derived_from_place_id: null,
trip_id: 5,
trip_title: 'Alps',
trip_owner_id: ME,
assignment_id: 100,
date: '2026-07-02',
participant_count: 0,
@@ -48,21 +44,15 @@ function track(overrides: Partial<TourStatsTrackRow> = {}): TourStatsTrackRow {
};
}
function stats(
executions: TourStatsExecutionRow[],
tracks: TourStatsTrackRow[] = [],
excluded: number[] = [],
userId = ME,
) {
return buildActivityStats({ userId, executions, tracks, excluded: new Set(excluded) });
function stats(executions: TourStatsExecutionRow[], tracks: TourStatsTrackRow[] = [], excluded: number[] = []) {
return buildActivityStats({ executions, tracks, excluded: new Set(excluded) });
}
describe('isOwnExecution (STA-02)', () => {
it('STA2-HELP-001: a day naming the user is theirs, a day naming nobody is the owner only', () => {
expect(isOwnExecution(row({ joined: 1, participant_count: 2, trip_owner_id: FRIEND }), ME)).toBe(true);
expect(isOwnExecution(row({ participant_count: 0 }), ME)).toBe(true);
expect(isOwnExecution(row({ participant_count: 0, trip_owner_id: FRIEND }), ME)).toBe(false);
expect(isOwnExecution(row({ participant_count: 1, joined: 0 }), ME)).toBe(false);
it('STA2-HELP-001: a day naming the user or nobody is theirs, one naming only others is not', () => {
expect(isOwnExecution(row({ joined: 1, participant_count: 2 }))).toBe(true);
expect(isOwnExecution(row({ participant_count: 0 }))).toBe(true);
expect(isOwnExecution(row({ participant_count: 1, joined: 0 }))).toBe(false);
});
});
@@ -75,6 +65,7 @@ describe('buildActivityStats (STA-02)', () => {
name: 'Ridge',
tour_type: 'hike',
trip: { id: 5, title: 'Alps' },
derived_from_place_id: null,
date: '2026-07-02',
basis: 'plan',
track: null,
@@ -89,14 +80,15 @@ describe('buildActivityStats (STA-02)', () => {
});
});
it('STA2-HELP-003: a tour on several days counts once, on its first day, saying on how many', () => {
it('STA2-HELP-003: a tour on several days counts once, on its last day, saying on how many', () => {
const { entries } = stats([
row({ assignment_id: 101, date: '2026-07-04' }),
row({ assignment_id: 100, date: '2026-07-02' }),
row({ assignment_id: 102, date: null }),
]);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({ date: '2026-07-02', day_count: 2 });
// Dated on the last day, so it is not done while it is still under way.
expect(entries[0]).toMatchObject({ date: '2026-07-04', day_count: 2 });
});
it('STA2-HELP-004: a linked recording replaces the plan and is no tour of its own', () => {
@@ -117,10 +109,10 @@ describe('buildActivityStats (STA-02)', () => {
expect(entries[0]?.distance_km).toBeCloseTo(2.22, 1);
});
it('STA2-HELP-005: a recording on no day counts on the first day; one recorded per day counts per day', () => {
it('STA2-HELP-005: a recording on no day counts on the last day; one recorded per day counts per day', () => {
const executions = [row({ assignment_id: 100 }), row({ assignment_id: 101, date: '2026-07-03' })];
const noDay = stats(executions, [track({ assignment_id: null })]);
expect(noDay.entries.map((entry) => entry.date)).toEqual(['2026-07-02']);
expect(noDay.entries.map((entry) => entry.date)).toEqual(['2026-07-03']);
const twice = stats(executions, [track(), track({ track_place_id: 21, assignment_id: 101 })]);
expect(twice.entries.map((entry) => [entry.date, entry.track?.place_id])).toEqual([
['2026-07-03', 21],
@@ -152,14 +144,15 @@ describe('buildActivityStats (STA-02)', () => {
expect(entries).toEqual([expect.objectContaining({ basis: 'plan', date: '2026-07-02' })]);
});
it('STA2-HELP-009: access to somebody else’s trip counts nothing; a day naming the user counts', () => {
const foreign = { trip_owner_id: FRIEND, trip_id: 6, trip_title: 'Theirs' };
expect(stats([row(foreign)]).entries).toEqual([]);
expect(stats([row({ ...foreign, participant_count: 2, joined: 1 })]).entries).toHaveLength(1);
expect(stats([row(foreign)]).uncounted).toEqual({ unassigned: 0, undated: 0 });
it('STA2-HELP-009: a day naming nobody counts for every member, on any trip the user can open', () => {
const shared = { trip_id: 6, trip_title: 'Theirs' };
expect(stats([row(shared)]).entries).toEqual([expect.objectContaining({ trip: { id: 6, title: 'Theirs' } })]);
expect(stats([row({ ...shared, participant_count: 2, joined: 1 })]).entries).toHaveLength(1);
const onNoDay = row({ ...shared, place_id: 11, assignment_id: null, date: null });
expect(stats([onNoDay]).uncounted).toEqual({ unassigned: 1, undated: 0 });
});
it('STA2-HELP-010: a day naming only others leaves the owner out, and says nothing about it', () => {
it('STA2-HELP-010: a day naming only others leaves the user out, and says nothing about it', () => {
expect(stats([row({ participant_count: 1, joined: 0 })])).toEqual({
entries: [],
uncounted: { unassigned: 0, undated: 0 },
@@ -175,7 +168,7 @@ describe('buildActivityStats (STA-02)', () => {
expect(result).toEqual({ entries: [], uncounted: { unassigned: 1, undated: 2 } });
});
it('STA2-HELP-012: a whole route does not count beside the stages planned from it', () => {
it('STA2-HELP-012: a whole route and the stages planned from it are all listed, each stage naming the route', () => {
const route = row({ place_id: 30, name: 'Whole route', distance: 60, assignment_id: 300, date: '2026-07-01' });
const stage1 = row({ place_id: 31, name: 'Stage 1', distance: 20, derived_from_place_id: 30, assignment_id: 301 });
const stage2 = row({
@@ -186,10 +179,22 @@ describe('buildActivityStats (STA-02)', () => {
assignment_id: 302,
date: '2026-07-03',
});
expect(stats([route, stage1, stage2]).entries.map((entry) => entry.place_id)).toEqual([32, 31]);
// Every entry is kept, each stage naming its route: whether a stage counts takes the reader's today.
const all = stats([route, stage1, stage2]).entries;
expect(all.map((entry) => [entry.place_id, entry.derived_from_place_id])).toEqual([
[32, 30],
[31, 30],
[30, null],
]);
// A route on no day whose stages are planned is not named as uncounted: its stages stand for it.
const routeOnNoDay = row({ ...route, assignment_id: null, date: null });
expect(stats([routeOnNoDay, stage1, stage2]).uncounted).toEqual({ unassigned: 0, undated: 0 });
// With no stage on a day, the route is what was done.
const unplanned = row({ ...stage1, assignment_id: null, date: null });
expect(stats([route, unplanned]).entries.map((entry) => entry.place_id)).toEqual([30]);
expect(stats([route, unplanned])).toMatchObject({
entries: [expect.objectContaining({ place_id: 30 })],
uncounted: { unassigned: 1, undated: 0 },
});
});
it('STA2-HELP-013: a paddle tour carries no heights, planned or recorded', () => {
@@ -13,7 +13,7 @@ import { makeDayAssignment } from '../../helpers/factories/itinerary';
import { makePlace } from '../../helpers/factories/places';
import { countRows } from '../../helpers/factories/rows';
import { makeTour } from '../../helpers/factories/tours';
import { makeDay, makeTrip } from '../../helpers/factories/trips';
import { addTripMember, makeDay, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
@@ -68,7 +68,7 @@ async function fixture() {
const closed = await makeTrip(orm(), stranger.id);
const hidden = await makePlace(orm(), closed.id, { name: 'Hidden' });
await makeTour(orm(), hidden.id);
return { user, tours, hidden };
return { user, trip, tours, hidden };
}
describe('TourActivityStatsMcp', () => {
@@ -118,4 +118,13 @@ describe('TourActivityStatsMcp', () => {
});
expect(await countRows(orm(), TourActivityExclusions)).toBe(0);
});
it('STA2-MCP-005: a member counts the days naming nobody, which are everyone’s, as over REST', async () => {
const { trip, tours } = await fixture();
const { user: member } = await makeUser(orm());
await addTripMember(orm(), trip.id, member.id);
const result = read(await mcp.getTourActivityStats({}, ctx(member.id)));
expect(result.tours.map((tour: { place_id: number }) => tour.place_id)).toEqual([tours.Lake, tours.Ridge]);
expect(result.upcoming).toBe(1);
});
});
@@ -46,8 +46,9 @@ const RECORDED = JSON.stringify([
/**
* The user's trip with a hike on a day and a paddle tour recorded on another;
* a trip of a friend the user is a member of, with one tour the friend did
* alone and one the user is named on; and a trip the user cannot open.
* a trip of a friend the user is a member of, with one tour whose day names
* only the friend, one naming only the user and one naming nobody, which is
* everyone's; and a trip the user cannot open.
*/
async function fixture() {
const { user } = await makeUser(orm());
@@ -74,7 +75,11 @@ async function fixture() {
const theirDay = await makeDay(orm(), theirs.id, { date: '2026-08-10' });
const alone = await makePlace(orm(), theirs.id, { name: 'Alone' });
await makeTour(orm(), alone.id, { distance: 30 });
await makeDayAssignment(orm(), theirDay.id, alone.id);
const aloneOn = await makeDayAssignment(orm(), theirDay.id, alone.id);
await insertRow(orm(), AssignmentParticipants, { assignment: aloneOn.id, user: friend.id });
const everyone = await makePlace(orm(), theirs.id, { name: 'Everyone' });
await makeTour(orm(), everyone.id, { distance: 5 });
await makeDayAssignment(orm(), theirDay.id, everyone.id);
const together = await makePlace(orm(), theirs.id, { name: 'Together' });
await makeTour(orm(), together.id, { distance: 7 });
const togetherOn = await makeDayAssignment(orm(), theirDay.id, together.id);
@@ -85,34 +90,35 @@ async function fixture() {
const hidden = await makePlace(orm(), closed.id, { name: 'Hidden' });
await makeTour(orm(), hidden.id);
await makeDayAssignment(orm(), closedDay.id, hidden.id);
return { user, friend, hike, paddle, watch, alone, together, togetherOn, hidden };
return { user, friend, hike, paddle, watch, alone, everyone, together, togetherOn, hidden };
}
describe('TourActivityStatsService', () => {
it('STA2-SVC-001: lists the own tours of every trip the user can open, plan or recording, newest first', async () => {
const { user, hike, paddle, watch, together } = await fixture();
const { user, hike, paddle, watch, everyone, together } = await fixture();
const result = await service.stats(user.id);
expect(result.entries.map((entry) => [entry.place_id, entry.basis, entry.date])).toEqual([
[everyone.id, 'plan', '2026-08-10'],
[together.id, 'plan', '2026-08-10'],
[paddle.id, 'track', '2026-07-03'],
[hike.id, 'plan', '2026-07-02'],
]);
expect(result.entries[1]).toMatchObject({
expect(result.entries[2]).toMatchObject({
tour_type: 'kayak',
trip: { title: 'Alps' },
track: { place_id: watch.id, name: 'Watch export' },
ascent_m: null,
descent_m: null,
});
expect(result.entries[1]?.distance_km).toBeCloseTo(2.35, 1);
expect(result.entries[2]?.distance_km).toBeCloseTo(2.35, 1);
expect(result.uncounted).toEqual({ unassigned: 1, undated: 0 });
});
it('STA2-SVC-002: the friend sees the tour they did alone, and not the user’s trip they cannot open', async () => {
const { friend, alone, together } = await fixture();
it('STA2-SVC-002: the friend sees their own and everyone’s tours, and not the user’s trip they cannot open', async () => {
const { friend, alone, everyone, together } = await fixture();
const result = await service.stats(friend.id);
// Together names only the user, so it is not the friend's, owner or not.
expect(result.entries.map((entry) => entry.place_id)).toEqual([alone.id]);
expect(result.entries.map((entry) => entry.place_id)).toEqual([alone.id, everyone.id]);
expect(result.entries.some((entry) => entry.place_id === together.id)).toBe(false);
});