mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-23 07:26:30 +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,89 @@
|
||||
import { idSchema } from '../common/primitives.schema';
|
||||
import { tourTypeKeySchema } from './tours.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* STA-02: the user's own tour activities, as the Atlas sums them. One entry is
|
||||
* one tour the user did on one day of a trip, read from what the trip holds:
|
||||
*
|
||||
* - The plan's values stand in for the tour while nothing was recorded
|
||||
* (`basis: 'plan'`), and say so. A tour on several days still counts once
|
||||
* (`day_count` says on how many), on the first of them.
|
||||
* - A recorded track linked to an execution of the tour (ACT-01) takes the
|
||||
* plan's place (`basis: 'track'`), one entry per recording; the plan of that
|
||||
* tour is then not counted besides it, and the recording is never counted as
|
||||
* a tour of its own.
|
||||
* - An import some other tour of the trip was planned from (the whole route a
|
||||
* multi-day tour's stages were cut from) is left out while one of those
|
||||
* tours counts, so the route and its stages are never added up together.
|
||||
* - Only the user's own part counts: an execution names the user as one of its
|
||||
* participants, or names none and the trip is the user's own. Being able to
|
||||
* open someone else's trip makes none of its tours the user's.
|
||||
*
|
||||
* Whether an entry is done is the reader's question (`date` before today, in
|
||||
* the reader's own time zone): the server answers every entry it found, the
|
||||
* upcoming ones too, so the app can say how many are still ahead.
|
||||
*/
|
||||
|
||||
/** Where an entry's values come from: the trip's planning, or a track recorded while doing it. */
|
||||
export const TOUR_ACTIVITY_BASES = ['plan', 'track'] as const;
|
||||
export const tourActivityBasisSchema = z.enum(TOUR_ACTIVITY_BASES);
|
||||
export type TourActivityBasis = z.infer<typeof tourActivityBasisSchema>;
|
||||
|
||||
/** A calendar day, YYYY-MM-DD, as a trip's days carry it. */
|
||||
export const tourActivityDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
|
||||
export const tourActivityStatsEntrySchema = z.object({
|
||||
place_id: idSchema,
|
||||
name: z.string(),
|
||||
tour_type: tourTypeKeySchema,
|
||||
trip: z.object({ id: idSchema, title: z.string() }),
|
||||
/** The day it was done on: the recording's day, else the first of the user's dated days the tour is on. */
|
||||
date: tourActivityDateSchema,
|
||||
basis: tourActivityBasisSchema,
|
||||
/** The recording whose values these are; null for the plan. */
|
||||
track: z.object({ place_id: idSchema, name: z.string() }).nullable(),
|
||||
/** On how many of the user's dated days the tour is planned; it counts once however many. */
|
||||
day_count: z.number().int().positive(),
|
||||
/** Null where the source does not know the value; a paddle tour never has heights. */
|
||||
distance_km: z.number().nonnegative().nullable(),
|
||||
ascent_m: z.number().nonnegative().nullable(),
|
||||
descent_m: z.number().nonnegative().nullable(),
|
||||
/** Left out of the user's sums on purpose (a tour that fell through); the plan stays as it is. */
|
||||
excluded: z.boolean(),
|
||||
});
|
||||
export type TourActivityStatsEntry = z.infer<typeof tourActivityStatsEntrySchema>;
|
||||
|
||||
export const tourActivityStatsResponseSchema = z.object({
|
||||
/** The newest first. */
|
||||
entries: z.array(tourActivityStatsEntrySchema),
|
||||
/**
|
||||
* Tours of the user's own trips that cannot count as done: on no day at all,
|
||||
* or only on days without a date. Said, so a missing tour is not a mystery.
|
||||
*/
|
||||
uncounted: z.object({
|
||||
unassigned: z.number().int().nonnegative(),
|
||||
undated: z.number().int().nonnegative(),
|
||||
}),
|
||||
});
|
||||
export type TourActivityStatsResponse = z.infer<typeof tourActivityStatsResponseSchema>;
|
||||
|
||||
/** Leaving a tour out of the user's own sums, or counting it again. Nothing of the tour changes. */
|
||||
export const tourActivityExclusionRequestSchema = z
|
||||
.object({
|
||||
place_id: idSchema,
|
||||
excluded: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
export type TourActivityExclusionRequest = z.infer<typeof tourActivityExclusionRequestSchema>;
|
||||
|
||||
/** What a reader narrows the sums by: a period (both days included) and one type. */
|
||||
export const tourActivityStatsQuerySchema = z
|
||||
.object({
|
||||
from: tourActivityDateSchema.optional(),
|
||||
to: tourActivityDateSchema.optional(),
|
||||
type: tourTypeKeySchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
export type TourActivityStatsQuery = z.infer<typeof tourActivityStatsQuerySchema>;
|
||||
@@ -0,0 +1,186 @@
|
||||
import { isTourActivityDone, summarizeTourActivities } from './tour-activity-stats';
|
||||
import {
|
||||
tourActivityExclusionRequestSchema,
|
||||
tourActivityStatsQuerySchema,
|
||||
tourActivityStatsResponseSchema,
|
||||
type TourActivityStatsEntry,
|
||||
} from './tour-activity-stats.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||
return {
|
||||
place_id: 1,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
trip: { id: 5, title: 'Alps' },
|
||||
date: '2026-07-02',
|
||||
basis: 'plan',
|
||||
track: null,
|
||||
day_count: 1,
|
||||
distance_km: 10,
|
||||
ascent_m: 500,
|
||||
descent_m: 400,
|
||||
excluded: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const TODAY = '2026-10-20';
|
||||
|
||||
describe('STA-02 tour activity stats contract', () => {
|
||||
it('STA2-SCHEMA-001: reads entries of either basis with unknown values kept unknown', () => {
|
||||
const body = {
|
||||
entries: [
|
||||
entry(),
|
||||
entry({
|
||||
place_id: 2,
|
||||
basis: 'track',
|
||||
track: { place_id: 9, name: 'Watch export' },
|
||||
distance_km: null,
|
||||
ascent_m: null,
|
||||
descent_m: null,
|
||||
}),
|
||||
],
|
||||
uncounted: { unassigned: 1, undated: 0 },
|
||||
};
|
||||
expect(tourActivityStatsResponseSchema.parse(body)).toEqual(body);
|
||||
});
|
||||
|
||||
it('STA2-SCHEMA-002: refuses a date that is not a calendar day, a negative distance and an unknown basis', () => {
|
||||
const uncounted = { unassigned: 0, undated: 0 };
|
||||
const parses = (entries: unknown[]) => tourActivityStatsResponseSchema.safeParse({ entries, uncounted }).success;
|
||||
expect(parses([entry({ date: '02.07.2026' })])).toBe(false);
|
||||
expect(parses([entry({ distance_km: -1 })])).toBe(false);
|
||||
expect(parses([{ ...entry(), basis: 'guess' }])).toBe(false);
|
||||
});
|
||||
|
||||
it('STA2-SCHEMA-003: the exclusion names one tour and a yes or no, nothing else', () => {
|
||||
expect(tourActivityExclusionRequestSchema.parse({ place_id: 4, excluded: true })).toEqual({
|
||||
place_id: 4,
|
||||
excluded: true,
|
||||
});
|
||||
expect(tourActivityExclusionRequestSchema.safeParse({ place_id: 4 }).success).toBe(false);
|
||||
const withNote = { place_id: 4, excluded: true, note: 'rain' };
|
||||
expect(tourActivityExclusionRequestSchema.safeParse(withNote).success).toBe(false);
|
||||
});
|
||||
|
||||
it('STA2-SCHEMA-004: the query takes a period and a type, all of them optional', () => {
|
||||
expect(tourActivityStatsQuerySchema.parse({})).toEqual({});
|
||||
expect(tourActivityStatsQuerySchema.parse({ from: '2026-01-01', to: '2026-12-31', type: 'kayak' })).toEqual({
|
||||
from: '2026-01-01',
|
||||
to: '2026-12-31',
|
||||
type: 'kayak',
|
||||
});
|
||||
expect(tourActivityStatsQuerySchema.safeParse({ type: 'car' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('STA-02 summarizeTourActivities', () => {
|
||||
it('STA2-SUM-001: a tour counts from the day after its day, not on it', () => {
|
||||
expect(isTourActivityDone(entry({ date: '2026-10-19' }), TODAY)).toBe(true);
|
||||
expect(isTourActivityDone(entry({ date: TODAY }), TODAY)).toBe(false);
|
||||
const summary = summarizeTourActivities([entry({ date: '2026-10-19' }), entry({ place_id: 2, date: TODAY })], {
|
||||
today: TODAY,
|
||||
});
|
||||
expect(summary.totals.count).toBe(1);
|
||||
expect(summary.upcoming).toBe(1);
|
||||
});
|
||||
|
||||
it('STA2-SUM-002: sums distance and heights, says how many rest on the plan and how many on a track', () => {
|
||||
const summary = summarizeTourActivities(
|
||||
[
|
||||
entry(),
|
||||
entry({
|
||||
place_id: 2,
|
||||
basis: 'track',
|
||||
track: { place_id: 9, name: 'Watch' },
|
||||
distance_km: 12.5,
|
||||
ascent_m: 650,
|
||||
descent_m: 600,
|
||||
}),
|
||||
],
|
||||
{ today: TODAY },
|
||||
);
|
||||
expect(summary.totals).toEqual({
|
||||
count: 2,
|
||||
distanceKm: { value: 22.5, known: 2, of: 2 },
|
||||
ascentM: { value: 1150, known: 2, of: 2 },
|
||||
descentM: { value: 1000, known: 2, of: 2 },
|
||||
byBasis: { plan: 1, track: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('STA2-SUM-003: an unknown value is no zero: the sum says it is short of the whole, or null when nobody knows', () => {
|
||||
const summary = summarizeTourActivities(
|
||||
[
|
||||
entry({ ascent_m: null, descent_m: null }),
|
||||
entry({ place_id: 2, distance_km: null, ascent_m: null, descent_m: null }),
|
||||
],
|
||||
{ today: TODAY },
|
||||
);
|
||||
expect(summary.totals.distanceKm).toEqual({ value: 10, known: 1, of: 2 });
|
||||
expect(summary.totals.ascentM).toEqual({ value: null, known: 0, of: 2 });
|
||||
});
|
||||
|
||||
it('STA2-SUM-004: paddling sums no heights, so a paddle tour leaves the height sums complete', () => {
|
||||
const summary = summarizeTourActivities(
|
||||
[entry(), entry({ place_id: 2, tour_type: 'kayak', distance_km: 8, ascent_m: null, descent_m: null })],
|
||||
{ today: TODAY },
|
||||
);
|
||||
expect(summary.totals.distanceKm).toEqual({ value: 18, known: 2, of: 2 });
|
||||
expect(summary.totals.ascentM).toEqual({ value: 500, known: 1, of: 1 });
|
||||
expect(summary.types.find((type) => type.type === 'kayak')?.ascentM).toEqual({ value: null, known: 0, of: 0 });
|
||||
});
|
||||
|
||||
it('STA2-SUM-005: narrows by period (both days included) and by type, the most tours of a type first', () => {
|
||||
const entries = [
|
||||
entry({ place_id: 1, date: '2025-12-31' }),
|
||||
entry({ place_id: 2, date: '2026-01-01', tour_type: 'bike' }),
|
||||
entry({ place_id: 3, date: '2026-06-30', tour_type: 'kayak' }),
|
||||
entry({ place_id: 4, date: '2026-07-01', tour_type: 'kayak' }),
|
||||
];
|
||||
const year = summarizeTourActivities(entries, { today: TODAY, from: '2026-01-01', to: '2026-12-31' });
|
||||
expect(year.totals.count).toBe(3);
|
||||
expect(year.types.map((type) => [type.type, type.count])).toEqual([
|
||||
['kayak', 2],
|
||||
['bike', 1],
|
||||
]);
|
||||
const paddled = summarizeTourActivities(entries, { today: TODAY, type: 'kayak' });
|
||||
expect(paddled.totals.distanceKm.value).toBe(20);
|
||||
expect(paddled.done.map((item) => item.place_id)).toEqual([4, 3]);
|
||||
});
|
||||
|
||||
it('STA2-SUM-006: an excluded tour is listed among the done ones but never summed, nor counted as upcoming', () => {
|
||||
const summary = summarizeTourActivities(
|
||||
[
|
||||
entry({ excluded: true }),
|
||||
entry({ place_id: 2, date: '2026-07-03' }),
|
||||
entry({ place_id: 3, date: '2026-12-01', excluded: true }),
|
||||
],
|
||||
{ today: TODAY },
|
||||
);
|
||||
expect(summary.totals.count).toBe(1);
|
||||
expect(summary.done.map((item) => [item.place_id, item.excluded])).toEqual([
|
||||
[2, false],
|
||||
[1, true],
|
||||
]);
|
||||
expect(summary.upcoming).toBe(0);
|
||||
});
|
||||
|
||||
it('STA2-SUM-007: nothing done is an empty summary, not a row of zeros', () => {
|
||||
const summary = summarizeTourActivities([], { today: TODAY });
|
||||
expect(summary.totals.count).toBe(0);
|
||||
expect(summary.totals.distanceKm.value).toBeNull();
|
||||
expect(summary.types).toEqual([]);
|
||||
expect(summary.done).toEqual([]);
|
||||
});
|
||||
|
||||
it('STA2-SUM-008: the same day sorts by name, so the list keeps its order between reads', () => {
|
||||
const summary = summarizeTourActivities(
|
||||
[entry({ place_id: 1, name: 'Zugspitze' }), entry({ place_id: 2, name: 'Alpspitze' })],
|
||||
{ today: TODAY },
|
||||
);
|
||||
expect(summary.done.map((item) => item.name)).toEqual(['Alpspitze', 'Zugspitze']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { TourActivityBasis, TourActivityStatsEntry } from './tour-activity-stats.schema';
|
||||
import type { TourTypeKey } from './tours.schema';
|
||||
|
||||
/**
|
||||
* STA-02: what the user's done tours add up to, for the Atlas and for the
|
||||
* assistant alike, so both say the same numbers. A sum knows how many entries
|
||||
* had the value and of how many could: `value` is null when none had it, never
|
||||
* a zero standing in for "unknown", and `known < of` says it is short of the
|
||||
* whole. Paddling sums no heights (a climb on the water says nothing), as in
|
||||
* the trip's own tour totals (STA-01).
|
||||
*/
|
||||
export interface TourActivitySum {
|
||||
value: number | null;
|
||||
known: number;
|
||||
of: number;
|
||||
}
|
||||
|
||||
export interface TourActivityTotals {
|
||||
count: number;
|
||||
distanceKm: TourActivitySum;
|
||||
ascentM: TourActivitySum;
|
||||
descentM: TourActivitySum;
|
||||
/** How many of the entries rest on the plan and how many on a recorded track. */
|
||||
byBasis: Record<TourActivityBasis, number>;
|
||||
}
|
||||
|
||||
export interface TourActivityFilter {
|
||||
/** Today in the reader's own calendar, YYYY-MM-DD: a tour counts once its day is over. */
|
||||
today: string;
|
||||
/** The period, both days included; left out, open on that side. */
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
/** One type; left out, all of them. */
|
||||
type?: TourTypeKey | null;
|
||||
}
|
||||
|
||||
export interface TourActivitySummary {
|
||||
totals: TourActivityTotals;
|
||||
/** By type, the most tours first; empty when nothing counts. */
|
||||
types: Array<TourActivityTotals & { type: TourTypeKey }>;
|
||||
/** Every entry done in the period, the newest first; those the user left out are among them, flagged and not summed. */
|
||||
done: TourActivityStatsEntry[];
|
||||
/** In the period and of the type, but their day is not over yet. */
|
||||
upcoming: number;
|
||||
}
|
||||
|
||||
/** Whether the day an entry is on is over: it counts from the next day on. */
|
||||
export function isTourActivityDone(entry: Pick<TourActivityStatsEntry, 'date'>, today: string): boolean {
|
||||
return entry.date < today;
|
||||
}
|
||||
|
||||
function inPeriod(date: string, filter: TourActivityFilter): boolean {
|
||||
return (!filter.from || date >= filter.from) && (!filter.to || date <= filter.to);
|
||||
}
|
||||
|
||||
function sumOf(values: ReadonlyArray<number | null>): TourActivitySum {
|
||||
const known = values.filter((value): value is number => value !== null && Number.isFinite(value));
|
||||
return {
|
||||
value: known.length ? known.reduce((total, value) => total + value, 0) : null,
|
||||
known: known.length,
|
||||
of: values.length,
|
||||
};
|
||||
}
|
||||
|
||||
function totalsOf(entries: readonly TourActivityStatsEntry[]): TourActivityTotals {
|
||||
const withHeights = entries.filter((entry) => entry.tour_type !== 'kayak');
|
||||
return {
|
||||
count: entries.length,
|
||||
distanceKm: sumOf(entries.map((entry) => entry.distance_km)),
|
||||
ascentM: sumOf(withHeights.map((entry) => entry.ascent_m)),
|
||||
descentM: sumOf(withHeights.map((entry) => entry.descent_m)),
|
||||
byBasis: {
|
||||
plan: entries.filter((entry) => entry.basis === 'plan').length,
|
||||
track: entries.filter((entry) => entry.basis === 'track').length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The entries of the period and type, done and counted, summed as a whole and by type. */
|
||||
export function summarizeTourActivities(
|
||||
entries: readonly TourActivityStatsEntry[],
|
||||
filter: TourActivityFilter,
|
||||
): TourActivitySummary {
|
||||
const matching = entries.filter(
|
||||
(entry) => inPeriod(entry.date, filter) && (!filter.type || entry.tour_type === filter.type),
|
||||
);
|
||||
const done = matching.filter((entry) => isTourActivityDone(entry, filter.today));
|
||||
const counted = done.filter((entry) => !entry.excluded);
|
||||
const byType = new Map<TourTypeKey, TourActivityStatsEntry[]>();
|
||||
for (const entry of counted) byType.set(entry.tour_type, [...(byType.get(entry.tour_type) ?? []), entry]);
|
||||
return {
|
||||
totals: totalsOf(counted),
|
||||
types: [...byType.entries()]
|
||||
.map(([type, ofType]) => ({ type, ...totalsOf(ofType) }))
|
||||
.sort((a, b) => b.count - a.count || a.type.localeCompare(b.type)),
|
||||
done: [...done].sort((a, b) => b.date.localeCompare(a.date) || a.name.localeCompare(b.name)),
|
||||
upcoming: matching.filter((entry) => !entry.excluded && !isTourActivityDone(entry, filter.today)).length,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user