mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
feat(atlas): sum up the tours you have done, by period and type (STA-02)
With the Tours addon on, the Atlas panel gets a third tab, Tours, beside
Stats and Bucket List: what you have done on your tours across all your
trips. A period (all time, this year, the last 12 months or an earlier year)
and a tour type narrow it; the tab shows the distance large with the number
of tours at its corner, the ascent and descent, and the types with their
distance. "Show tours" opens every tour of the period in a dialog with the
same filters, the sums, the split by type and one row per tour.
What counts is said, never guessed. A tour counts once the day it is on is
over, with the values of the planning, badged "Planned" and explained as
not measured. A linked actual track (ACT-01) replaces those values for its
execution, badged "Recorded" and named, and is never added on top nor
counted as a tour of its own. A tour on several days counts once, a whole
route does not count beside the stages planned from it, a paddle tour sums
no heights, and a value nobody knows stays out of the sum, which then reads
"at least". Only the user's own part counts: a day names them among its
participants, or names nobody on a trip of their own; being able to open
somebody else's trip makes none of its tours theirs. Tours still ahead, on
no day or only on undated days are named as not counting. A tour that fell
through can be left out of the sums ("Leave out"): it stays in the plan
and in the list, dimmed, and "Count again" brings it back. Only the user's
own numbers change.
Server: GET /api/tours/activity-stats answers the user's activity entries
across every trip they can open, and PUT /api/tours/activity-stats/exclusions
leaves a tour out or counts it again (the tour must be in such a trip, else
404). A tour_activity_exclusions table keeps the exclusions per user and
tour. The sums are added up by a shared summary in @trek/shared, so the
Atlas and the assistant say the same numbers. MCP: get_tour_activity_stats
and set_tour_activity_excluded over the same service. The tab reads live
and needs a connection, like the rest of the Atlas statistics.
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* TourActivityStatsController (STA-02): route metadata and delegation. The
|
||||
* sums and the access check live in TourActivityStatsService, which the MCP
|
||||
* tools call too; the service suite and the e2e suite hold those.
|
||||
*/
|
||||
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 { TRIP_PERMISSION_KEY } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import { TourActivityStatsController } from '../../../src/nest/tours/tour-activity-stats.controller';
|
||||
import type { TourActivityStatsService } from '../../../src/nest/tours/tour-activity-stats.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
import { tourActivityExclusionRequestSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../src/nest/permissions/permissions.service', () => ({ PermissionsService: class {} }));
|
||||
vi.mock('../../../src/nest/addons/addons.service', () => ({ AddonsService: class {} }));
|
||||
vi.mock('../../../src/nest/tours/tour-activity-stats.service', () => ({ TourActivityStatsService: class {} }));
|
||||
vi.mock('../../../src/nest/auth-core/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
|
||||
|
||||
const answer = { entries: [], uncounted: { unassigned: 0, undated: 0 } };
|
||||
|
||||
describe('TourActivityStatsController', () => {
|
||||
it('STA2-CTL-001: sits behind the addon and auth guards, not under a trip', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, TourActivityStatsController)).toBe('api/tours/activity-stats');
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, TourActivityStatsController)).toEqual([AddonGuard, JwtAuthGuard]);
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivityStatsController)).toEqual({
|
||||
addonId: 'tours',
|
||||
label: 'Tours',
|
||||
});
|
||||
});
|
||||
|
||||
it('STA2-CTL-002: GET reads the sums and PUT exclusions writes, both answering 200 without a trip permission', () => {
|
||||
const routes = [
|
||||
['list', RequestMethod.GET, '/'],
|
||||
['setExcluded', RequestMethod.PUT, 'exclusions'],
|
||||
] as const;
|
||||
for (const [handler, method, path] of routes) {
|
||||
const fn = TourActivityStatsController.prototype[handler];
|
||||
expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(method);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(path);
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, fn)).toBeUndefined();
|
||||
expect(Reflect.getMetadata(HTTP_CODE_METADATA, fn)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('STA2-CTL-003: GET hands the user to the service', async () => {
|
||||
const service = { stats: vi.fn().mockResolvedValue(answer) } as unknown as TourActivityStatsService;
|
||||
expect(await new TourActivityStatsController(service).list({ id: 3 } as User)).toBe(answer);
|
||||
expect(service.stats).toHaveBeenCalledWith(3);
|
||||
});
|
||||
|
||||
it('STA2-CTL-004: PUT hands the user and the validated body to the service', async () => {
|
||||
const service = { setExcluded: vi.fn().mockResolvedValue(answer) } as unknown as TourActivityStatsService;
|
||||
const body = tourActivityExclusionRequestSchema.parse({ place_id: 9, excluded: true });
|
||||
expect(await new TourActivityStatsController(service).setExcluded({ id: 3 } as User, body)).toBe(answer);
|
||||
expect(service.setExcluded).toHaveBeenCalledWith(3, body);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* STA-02, the pure half of the user's activity sums: whose tours count, on
|
||||
* which day, on what basis, and what is never added up twice.
|
||||
*/
|
||||
import type { TourStatsExecutionRow, TourStatsTrackRow } from '../../../src/db/repositories/TourActivities.repository';
|
||||
import { buildActivityStats, isOwnExecution } from '../../../src/nest/tours/tour-activity-stats.helpers';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const ME = 1;
|
||||
const FRIEND = 2;
|
||||
|
||||
function row(overrides: Partial<TourStatsExecutionRow> = {}): TourStatsExecutionRow {
|
||||
return {
|
||||
place_id: 10,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
distance: 12.5,
|
||||
elevation_gain: 800,
|
||||
elevation_loss: 790,
|
||||
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,
|
||||
joined: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
[47.02, 11, 650],
|
||||
]);
|
||||
|
||||
function track(overrides: Partial<TourStatsTrackRow> = {}): TourStatsTrackRow {
|
||||
return {
|
||||
place_id: 10,
|
||||
track_place_id: 20,
|
||||
assignment_id: 100,
|
||||
track_name: 'Watch export',
|
||||
track_route_geometry: LINE,
|
||||
track_recorded_route_geometry: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function stats(
|
||||
executions: TourStatsExecutionRow[],
|
||||
tracks: TourStatsTrackRow[] = [],
|
||||
excluded: number[] = [],
|
||||
userId = ME,
|
||||
) {
|
||||
return buildActivityStats({ userId, 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);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildActivityStats (STA-02)', () => {
|
||||
it('STA2-HELP-002: a planned tour on a dated day of the own trip counts with its plan', () => {
|
||||
expect(stats([row()])).toEqual({
|
||||
entries: [
|
||||
{
|
||||
place_id: 10,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
trip: { id: 5, title: 'Alps' },
|
||||
date: '2026-07-02',
|
||||
basis: 'plan',
|
||||
track: null,
|
||||
day_count: 1,
|
||||
distance_km: 12.5,
|
||||
ascent_m: 800,
|
||||
descent_m: 790,
|
||||
excluded: false,
|
||||
},
|
||||
],
|
||||
uncounted: { unassigned: 0, undated: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('STA2-HELP-003: a tour on several days counts once, on its first 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 });
|
||||
});
|
||||
|
||||
it('STA2-HELP-004: a linked recording replaces the plan and is no tour of its own', () => {
|
||||
const { entries } = stats(
|
||||
[row(), row({ place_id: 20, name: 'Watch export', assignment_id: null, date: null })],
|
||||
[track()],
|
||||
);
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
place_id: 10,
|
||||
basis: 'track',
|
||||
track: { place_id: 20, name: 'Watch export' },
|
||||
date: '2026-07-02',
|
||||
day_count: 1,
|
||||
ascent_m: 100,
|
||||
descent_m: 50,
|
||||
});
|
||||
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', () => {
|
||||
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']);
|
||||
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],
|
||||
['2026-07-02', 20],
|
||||
]);
|
||||
});
|
||||
|
||||
it('STA2-HELP-006: a recording is measured on the line it kept when it was planned over since', () => {
|
||||
const kept = JSON.stringify([
|
||||
[47, 11],
|
||||
[47.1, 11],
|
||||
]);
|
||||
const { entries } = stats([row()], [track({ track_recorded_route_geometry: kept })]);
|
||||
expect(entries[0]?.distance_km).toBeCloseTo(11.1, 0);
|
||||
expect(entries[0]).toMatchObject({ ascent_m: null, descent_m: null });
|
||||
});
|
||||
|
||||
it('STA2-HELP-007: a recording without a line knows no distance', () => {
|
||||
const { entries } = stats([row()], [track({ track_route_geometry: null })]);
|
||||
expect(entries[0]).toMatchObject({ basis: 'track', distance_km: null, ascent_m: null });
|
||||
});
|
||||
|
||||
it('STA2-HELP-008: the recording of somebody else’s day is theirs, so the plan stands for the user', () => {
|
||||
const executions = [
|
||||
row({ assignment_id: 100, participant_count: 0 }),
|
||||
row({ assignment_id: 101, date: '2026-07-03', participant_count: 1, joined: 0 }),
|
||||
];
|
||||
const { entries } = stats(executions, [track({ assignment_id: 101 })]);
|
||||
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-010: a day naming only others leaves the owner out, and says nothing about it', () => {
|
||||
expect(stats([row({ participant_count: 1, joined: 0 })])).toEqual({
|
||||
entries: [],
|
||||
uncounted: { unassigned: 0, undated: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('STA2-HELP-011: own tours on no day or only on undated days are named as not counting', () => {
|
||||
const result = stats([
|
||||
row({ place_id: 11, assignment_id: null, date: null }),
|
||||
row({ place_id: 12, assignment_id: 103, date: null }),
|
||||
row({ place_id: 13, assignment_id: 104, date: 'not a date' }),
|
||||
]);
|
||||
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', () => {
|
||||
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({
|
||||
place_id: 32,
|
||||
name: 'Stage 2',
|
||||
distance: 40,
|
||||
derived_from_place_id: 30,
|
||||
assignment_id: 302,
|
||||
date: '2026-07-03',
|
||||
});
|
||||
expect(stats([route, stage1, stage2]).entries.map((entry) => entry.place_id)).toEqual([32, 31]);
|
||||
// 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]);
|
||||
});
|
||||
|
||||
it('STA2-HELP-013: a paddle tour carries no heights, planned or recorded', () => {
|
||||
const paddle = row({ tour_type: 'kayak', elevation_gain: 12, elevation_loss: 12 });
|
||||
expect(stats([paddle]).entries[0]).toMatchObject({ ascent_m: null, descent_m: null, distance_km: 12.5 });
|
||||
expect(stats([paddle], [track()]).entries[0]).toMatchObject({ ascent_m: null, descent_m: null });
|
||||
});
|
||||
|
||||
it('STA2-HELP-014: an unknown or broken measure stays unknown, never zero or negative', () => {
|
||||
const { entries } = stats([row({ distance: null, elevation_gain: -5, elevation_loss: Number.NaN })]);
|
||||
expect(entries[0]).toMatchObject({ distance_km: null, ascent_m: null, descent_m: null });
|
||||
});
|
||||
|
||||
it('STA2-HELP-015: an excluded tour stays listed, flagged, with every entry of it', () => {
|
||||
const { entries } = stats([row()], [track()], [10]);
|
||||
expect(entries).toEqual([expect.objectContaining({ place_id: 10, excluded: true, basis: 'track' })]);
|
||||
});
|
||||
|
||||
it('STA2-HELP-016: the newest first, then by name; a timestamp on a day reads as its calendar day', () => {
|
||||
const { entries } = stats([
|
||||
row({ place_id: 1, name: 'Zugspitze', assignment_id: 1, date: '2026-07-02 00:00:00' }),
|
||||
row({ place_id: 2, name: 'Alpspitze', assignment_id: 2, date: '2026-07-02' }),
|
||||
row({ place_id: 3, name: 'Hochkalter', assignment_id: 3, date: '2026-08-01' }),
|
||||
]);
|
||||
expect(entries.map((entry) => [entry.name, entry.date])).toEqual([
|
||||
['Hochkalter', '2026-08-01'],
|
||||
['Alpspitze', '2026-07-02'],
|
||||
['Zugspitze', '2026-07-02'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* TourActivityStatsMcp (STA-02): the user's own tour activities and leaving
|
||||
* one out, over MCP, through the same service as the Atlas: the sums of a
|
||||
* period and a type, the tours they are made of and what they rest on. Today
|
||||
* is pinned, so a tour's day is over or not whenever the suite runs.
|
||||
*/
|
||||
import { TourActivityExclusions } from '../../../src/db/entities/TourActivityExclusions.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { TourActivityStatsMcp } from '../../../src/nest/tours/tour-activity-stats.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
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 { makeUser } from '../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let mcp: TourActivityStatsMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
mcp = t.get(TourActivityStatsMcp);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date('2026-07-10T12:00:00Z'));
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
afterAll(async () => {
|
||||
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);
|
||||
}
|
||||
|
||||
/** A hike and a paddle tour done in July, a hike still ahead, and a trip somebody else owns. */
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: stranger } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id, { title: 'Alps' });
|
||||
const tours: Record<string, number> = {};
|
||||
for (const [name, type, distance, date] of [
|
||||
['Ridge', 'hike', 12, '2026-07-02'],
|
||||
['Lake', 'kayak', 9, '2026-07-04'],
|
||||
['Summit', 'hike', 15, '2026-07-20'],
|
||||
] as const) {
|
||||
const day = await makeDay(orm(), trip.id, { date });
|
||||
const place = await makePlace(orm(), trip.id, { name });
|
||||
await makeTour(orm(), place.id, { tourTypeRef: type, distance, elevation_gain: 500, elevation_loss: 500 });
|
||||
await makeDayAssignment(orm(), day.id, place.id);
|
||||
tours[name] = place.id;
|
||||
}
|
||||
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 };
|
||||
}
|
||||
|
||||
describe('TourActivityStatsMcp', () => {
|
||||
it('STA2-MCP-001: get_tour_activity_stats sums the done tours, by type, and says what is still ahead', async () => {
|
||||
const { user, tours } = await fixture();
|
||||
const result = read(await mcp.getTourActivityStats({}, ctx(user.id)));
|
||||
expect(result.today).toBe('2026-07-10');
|
||||
expect(result.totals).toEqual({
|
||||
count: 2,
|
||||
distanceKm: { value: 21, known: 2, of: 2 },
|
||||
ascentM: { value: 500, known: 1, of: 1 },
|
||||
descentM: { value: 500, known: 1, of: 1 },
|
||||
byBasis: { plan: 2, track: 0 },
|
||||
});
|
||||
expect(result.by_type.map((type: { type: string }) => type.type)).toEqual(['hike', 'kayak']);
|
||||
expect(result.tours.map((tour: { place_id: number; basis: string }) => [tour.place_id, tour.basis])).toEqual([
|
||||
[tours.Lake, 'plan'],
|
||||
[tours.Ridge, 'plan'],
|
||||
]);
|
||||
expect(result.upcoming).toBe(1);
|
||||
expect(result.uncounted).toEqual({ unassigned: 0, undated: 0 });
|
||||
});
|
||||
|
||||
it('STA2-MCP-002: narrows by period and type', async () => {
|
||||
const { user, tours } = await fixture();
|
||||
const paddled = read(await mcp.getTourActivityStats({ type: 'kayak' }, ctx(user.id)));
|
||||
expect(paddled.tours.map((tour: { place_id: number }) => tour.place_id)).toEqual([tours.Lake]);
|
||||
const early = read(await mcp.getTourActivityStats({ from: '2026-07-01', to: '2026-07-03' }, ctx(user.id)));
|
||||
expect(early.totals.count).toBe(1);
|
||||
expect(early.upcoming).toBe(0);
|
||||
});
|
||||
|
||||
it('STA2-MCP-003: set_tour_activity_excluded leaves a tour out and counts it again', async () => {
|
||||
const { user, tours } = await fixture();
|
||||
const left = read(await mcp.setTourActivityExcluded({ place_id: tours.Ridge, excluded: true }, ctx(user.id)));
|
||||
expect(left.totals.count).toBe(1);
|
||||
expect(left.tours.find((tour: { place_id: number }) => tour.place_id === tours.Ridge)?.excluded).toBe(true);
|
||||
const back = read(await mcp.setTourActivityExcluded({ place_id: tours.Ridge, excluded: false }, ctx(user.id)));
|
||||
expect(back.totals.count).toBe(2);
|
||||
expect(await countRows(orm(), TourActivityExclusions)).toBe(0);
|
||||
});
|
||||
|
||||
it('STA2-MCP-004: a tour of a trip the user cannot open is not found, as over REST', async () => {
|
||||
const { user, hidden } = await fixture();
|
||||
expect(read(await mcp.setTourActivityExcluded({ place_id: hidden.id, excluded: true }, ctx(user.id)))).toEqual({
|
||||
error: 'Tour not found.',
|
||||
});
|
||||
expect(await countRows(orm(), TourActivityExclusions)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* TourActivityStatsService (STA-02): the user's own tour activities across
|
||||
* every trip they can open, and leaving one out of them. The service comes out
|
||||
* of ToursModule over a snapshot test db; rows are seeded through the ORM
|
||||
* factories.
|
||||
*/
|
||||
import { AssignmentParticipants } from '../../../src/db/entities/AssignmentParticipants.entity';
|
||||
import { TourActivityExclusions } from '../../../src/db/entities/TourActivityExclusions.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import { TourActivityStatsService } from '../../../src/nest/tours/tour-activity-stats.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { countRows, findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { makeTour, makeTourActivity } from '../../helpers/factories/tours';
|
||||
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';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let service: TourActivityStatsService;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
service = t.get(TourActivityStatsService);
|
||||
});
|
||||
beforeEach(() => resetTestDb(db));
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const RECORDED = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11.005, 760],
|
||||
[47.02, 11, 880],
|
||||
]);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: friend } = await makeUser(orm());
|
||||
const { user: stranger } = await makeUser(orm());
|
||||
|
||||
const trip = await makeTrip(orm(), user.id, { title: 'Alps' });
|
||||
const day1 = await makeDay(orm(), trip.id, { date: '2026-07-02' });
|
||||
const day2 = await makeDay(orm(), trip.id, { date: '2026-07-03' });
|
||||
const hike = await makePlace(orm(), trip.id, { name: 'Ridge' });
|
||||
await makeTour(orm(), hike.id, { distance: 12.5, elevation_gain: 800, elevation_loss: 790 });
|
||||
await makeDayAssignment(orm(), day1.id, hike.id);
|
||||
const paddle = await makePlace(orm(), trip.id, { name: 'Lake' });
|
||||
await makeTour(orm(), paddle.id, { tourTypeRef: 'kayak', distance: 9 });
|
||||
const onDay2 = await makeDayAssignment(orm(), day2.id, paddle.id);
|
||||
const watch = await makePlace(orm(), trip.id, { name: 'Watch export', route_geometry: RECORDED });
|
||||
await makeTour(orm(), watch.id, { origin: 'gpx' });
|
||||
await makeTourActivity(orm(), paddle.id, watch.id, { assignment: onDay2.id });
|
||||
const idle = await makePlace(orm(), trip.id, { name: 'Idle' });
|
||||
await makeTour(orm(), idle.id);
|
||||
|
||||
const theirs = await makeTrip(orm(), friend.id, { title: 'Theirs' });
|
||||
await addTripMember(orm(), theirs.id, user.id);
|
||||
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 together = await makePlace(orm(), theirs.id, { name: 'Together' });
|
||||
await makeTour(orm(), together.id, { distance: 7 });
|
||||
const togetherOn = await makeDayAssignment(orm(), theirDay.id, together.id);
|
||||
await insertRow(orm(), AssignmentParticipants, { assignment: togetherOn.id, user: user.id });
|
||||
|
||||
const closed = await makeTrip(orm(), stranger.id);
|
||||
const closedDay = await makeDay(orm(), closed.id, { date: '2026-07-01' });
|
||||
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 };
|
||||
}
|
||||
|
||||
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 result = await service.stats(user.id);
|
||||
expect(result.entries.map((entry) => [entry.place_id, entry.basis, entry.date])).toEqual([
|
||||
[together.id, 'plan', '2026-08-10'],
|
||||
[paddle.id, 'track', '2026-07-03'],
|
||||
[hike.id, 'plan', '2026-07-02'],
|
||||
]);
|
||||
expect(result.entries[1]).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.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();
|
||||
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.some((entry) => entry.place_id === together.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('STA2-SVC-003: leaving a tour out keeps it listed, flagged; counting it again clears the flag', async () => {
|
||||
const { user, hike } = await fixture();
|
||||
const left = await service.setExcluded(user.id, { place_id: hike.id, excluded: true });
|
||||
expect(left.entries.find((entry) => entry.place_id === hike.id)?.excluded).toBe(true);
|
||||
expect(await findRow(orm(), Tours, { place: hike.id })).toMatchObject({ distance: 12.5 });
|
||||
const back = await service.setExcluded(user.id, { place_id: hike.id, excluded: false });
|
||||
expect(back.entries.find((entry) => entry.place_id === hike.id)?.excluded).toBe(false);
|
||||
expect(await countRows(orm(), TourActivityExclusions, {})).toBe(0);
|
||||
});
|
||||
|
||||
it('STA2-SVC-004: a tour of a trip the user cannot open reads as missing and nothing is written', async () => {
|
||||
const { user, hidden } = await fixture();
|
||||
await expect(service.setExcluded(user.id, { place_id: hidden.id, excluded: true })).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
await expect(service.setExcluded(user.id, { place_id: 999_999, excluded: true })).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
expect(await countRows(orm(), TourActivityExclusions, {})).toBe(0);
|
||||
});
|
||||
|
||||
it('STA2-SVC-005: one user leaving a tour out changes nobody else’s list', async () => {
|
||||
const { user, friend, together, togetherOn } = await fixture();
|
||||
await insertRow(orm(), AssignmentParticipants, { assignment: togetherOn.id, user: friend.id });
|
||||
await service.setExcluded(user.id, { place_id: together.id, excluded: true });
|
||||
const friends = await service.stats(friend.id);
|
||||
expect(friends.entries.find((entry) => entry.place_id === together.id)?.excluded).toBe(false);
|
||||
});
|
||||
|
||||
it('STA2-SVC-006: a user without trips has nothing to count', async () => {
|
||||
const { user } = await makeUser(orm());
|
||||
expect(await service.stats(user.id)).toEqual({ entries: [], uncounted: { unassigned: 0, undated: 0 } });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user