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:
Maurice
2026-10-20 13:43:12 +02:00
parent ae79ab8dad
commit bde2ad2ca8
76 changed files with 4717 additions and 16 deletions
+4 -3
View File
@@ -42,14 +42,15 @@ describe('ALL_ENTITIES', () => {
* + paddle_water_graphs and paddle_region_requests, a region's water network and the regions that wait for an admin
* + tour_station_visits, how far a city walk got on one of its days
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
* + tour_activities, the recorded tracks assigned to a tour)
* + tour_activities, the recorded tracks assigned to a tour
* + tour_activity_exclusions, the tours a user left out of their own activity sums)
* 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 145 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(145);
it('ENT-003: exactly 146 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(146);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -39,7 +39,8 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// + tour_change_steps: id, place_id, proposal_id, base_revision, revision, changes, before_state (a step is
// only ever written whole, by the save of a confirmed change).
// + tour_activities: id, place_id, track_place_id (an assignment always names its tour and its recording).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 507;
// + tour_activity_exclusions: id, user_id, place_id (an exclusion always names its user and its tour).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 510;
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', () => {
@@ -73,6 +73,7 @@ const UNNUMBERED = [
'Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal',
'Migration20200101045710_a_saved_tour_change_can_be_taken_back',
'Migration20200101045900_a_tour_keeps_the_track_it_was_done_with',
'Migration20200101045910_a_tour_can_be_left_out_of_ones_activities',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,130 @@
/**
* `TourActivitiesRepository`, the STA-02 reads: every tour of the trips the
* user can open, once per day it is on, with the day's date, the trip's owner
* and who the day names as taking part; and the recordings assigned to them
* with their lines. Seeded through the ORM factories over the migrated
* snapshot schema.
*/
import { AssignmentParticipants } from '../../../../src/db/entities/AssignmentParticipants.entity';
import { TourActivities } from '../../../../src/db/entities/TourActivities.entity';
import type { TourActivitiesRepository } from '../../../../src/db/repositories/TourActivities.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeDayAssignment } from '../../../helpers/factories/itinerary';
import { makePlace } from '../../../helpers/factories/places';
import { insertRow } from '../../../helpers/factories/rows';
import { makeTour, makeTourActivity } from '../../../helpers/factories/tours';
import { makeDay, makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: TourActivitiesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(TourActivities);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const LINE = JSON.stringify([
[47, 11, 600],
[47.01, 11, 700],
]);
/** A hike on a dated day with a friend named on it, a tour on no day, a recording, and a trip of somebody else. */
async function fixture() {
const { user } = await makeUser(t);
const { user: friend } = await makeUser(t);
const trip = await makeTrip(t, user.id, { title: 'Alps' });
const day = await makeDay(t, trip.id, { date: '2026-07-02' });
const undated = await makeDay(t, trip.id);
const hike = await makePlace(t, trip.id, { name: 'Ridge' });
await makeTour(t, hike.id, { distance: 12.5, elevation_gain: 800, elevation_loss: 790 });
const onDay = await makeDayAssignment(t, day.id, hike.id);
const onUndated = await makeDayAssignment(t, undated.id, hike.id);
await insertRow(t, AssignmentParticipants, { assignment: onDay.id, user: friend.id });
const idle = await makePlace(t, trip.id, { name: 'Idle' });
await makeTour(t, idle.id);
const watch = await makePlace(t, trip.id, { name: 'Watch export', route_geometry: LINE });
await makeTour(t, watch.id, { origin: 'gpx' });
const theirs = await makeTrip(t, friend.id, { title: 'Theirs' });
const theirTour = await makePlace(t, theirs.id, { name: 'Their tour' });
await makeTour(t, theirTour.id);
return { user, friend, trip, day, hike, onDay, onUndated, idle, watch, theirs, theirTour };
}
describe('TourActivitiesRepository stats reads (STA-02)', () => {
it('STA2-REPO-010: lists each tour once per day it is on, once without a day, with the day and the trip', async () => {
const { user, friend, trip, hike, onDay, onUndated, idle, watch } = await fixture();
const rows = await repo.listExecutionsForStats([trip.id], user.id);
expect(rows.map((row) => [row.place_id, row.assignment_id, row.date])).toEqual([
[hike.id, onDay.id, '2026-07-02'],
[hike.id, onUndated.id, null],
[idle.id, null, null],
[watch.id, null, null],
]);
expect(rows[0]).toMatchObject({
name: 'Ridge',
tour_type: 'hike',
distance: 12.5,
elevation_gain: 800,
elevation_loss: 790,
derived_from_place_id: null,
trip_id: trip.id,
trip_title: 'Alps',
trip_owner_id: user.id,
participant_count: 1,
joined: 0,
});
expect(rows[1]).toMatchObject({ participant_count: 0, joined: 0 });
const asFriend = await repo.listExecutionsForStats([trip.id], friend.id);
expect(asFriend[0]).toMatchObject({ participant_count: 1, joined: 1 });
});
it('STA2-REPO-011: never reaches a trip outside the ids given, and reads nothing for none', async () => {
const { user, trip, theirs, theirTour } = await fixture();
const rows = await repo.listExecutionsForStats([trip.id], user.id);
expect(rows.some((row) => row.place_id === theirTour.id)).toBe(false);
expect((await repo.listExecutionsForStats([theirs.id], user.id)).map((row) => row.place_id)).toEqual([
theirTour.id,
]);
expect(await repo.listExecutionsForStats([], user.id)).toEqual([]);
});
it('STA2-REPO-012: a day of another trip gives no date', async () => {
const { user, trip, theirs, idle } = await fixture();
const foreignDay = await makeDay(t, theirs.id, { date: '2026-08-01' });
await makeDayAssignment(t, foreignDay.id, idle.id);
const rows = await repo.listExecutionsForStats([trip.id], user.id);
expect(rows.filter((row) => row.place_id === idle.id).map((row) => row.date)).toEqual([null]);
});
it('STA2-REPO-013: lists the recordings of the trips with the lines they were recorded with', async () => {
const { trip, hike, onDay, watch, theirs } = await fixture();
await makeTourActivity(t, hike.id, watch.id, { assignment: onDay.id });
expect(await repo.listTracksForStats([trip.id])).toEqual([
{
place_id: hike.id,
track_place_id: watch.id,
assignment_id: onDay.id,
track_name: 'Watch export',
track_route_geometry: LINE,
track_recorded_route_geometry: null,
},
]);
expect(await repo.listTracksForStats([theirs.id])).toEqual([]);
expect(await repo.listTracksForStats([])).toEqual([]);
});
});
@@ -0,0 +1,89 @@
/**
* `TourActivityExclusionsRepository` (STA-02): the tours a user left out of
* their own activity sums. Personal throughout: one user's rows never reach
* another's reads or writes. Seeded through the ORM factories over the
* migrated snapshot schema.
*/
import { Places } from '../../../../src/db/entities/Places.entity';
import { TourActivityExclusions } from '../../../../src/db/entities/TourActivityExclusions.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { TourActivityExclusionsRepository } from '../../../../src/db/repositories/TourActivityExclusions.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makePlace } from '../../../helpers/factories/places';
import { countRows, deleteRows, findRow } from '../../../helpers/factories/rows';
import { makeTour } from '../../../helpers/factories/tours';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: TourActivityExclusionsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(TourActivityExclusions);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
/** Two users, one trip with two tours. */
async function fixture() {
const { user } = await makeUser(t);
const { user: friend } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const ridge = await makePlace(t, trip.id, { name: 'Ridge' });
await makeTour(t, ridge.id);
const lake = await makePlace(t, trip.id, { name: 'Lake' });
await makeTour(t, lake.id, { tourTypeRef: 'kayak' });
return { user, friend, ridge, lake };
}
describe('TourActivityExclusionsRepository', () => {
it('STA2-REPO-001: exclude writes one row per user and tour, a second call changes nothing', async () => {
const { user, ridge, lake } = await fixture();
await repo.exclude(user.id, lake.id);
await repo.exclude(user.id, ridge.id);
await repo.exclude(user.id, ridge.id);
expect(await repo.listPlaceIds(user.id)).toEqual([ridge.id, lake.id].sort((a, b) => a - b));
expect(await countRows(t, TourActivityExclusions, { user: user.id })).toBe(2);
expect((await findRow(t, TourActivityExclusions, { user: user.id, place: ridge.id }))?.excluded_at).toMatch(
/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,
);
});
it('STA2-REPO-002: one user leaving a tour out leaves it in for everybody else', async () => {
const { user, friend, ridge } = await fixture();
await repo.exclude(user.id, ridge.id);
expect(await repo.listPlaceIds(friend.id)).toEqual([]);
await repo.include(friend.id, ridge.id);
expect(await repo.listPlaceIds(user.id)).toEqual([ridge.id]);
});
it('STA2-REPO-003: include counts the tour again, and is a no-op for a tour never left out', async () => {
const { user, ridge, lake } = await fixture();
await repo.exclude(user.id, ridge.id);
await repo.include(user.id, lake.id);
await repo.include(user.id, ridge.id);
expect(await repo.listPlaceIds(user.id)).toEqual([]);
});
it('STA2-REPO-004: deleting the tour or the user takes the row along', async () => {
const { user, friend, ridge, lake } = await fixture();
await repo.exclude(user.id, ridge.id);
await repo.exclude(friend.id, lake.id);
await deleteRows(t, Places, { id: ridge.id });
expect(await repo.listPlaceIds(user.id)).toEqual([]);
await deleteRows(t, Users, { id: friend.id });
expect(await countRows(t, TourActivityExclusions, {})).toBe(0);
});
});