feat(tours): city walks in the contract and on the server (CW-01, CW-02, CW-03, CW-09, CW-10)

A tour can be a city walk. Its points are stations that keep a key across
saves, a name, a stay (0 for a point passed through, empty when unknown), an
importance and a protection; the visits of a walk's stations are kept per day
assignment, so another day or a copy starts with nothing visited. A station
that is gone takes its visits with it. An assistant reads how far a walk got
on a day, what is open and which times are known.
This commit is contained in:
Maurice
2026-10-19 21:59:47 +02:00
parent e3268735f2
commit d5d2d6b25e
26 changed files with 684 additions and 31 deletions
@@ -0,0 +1,34 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourStationVisitsRepository } from '../repositories/TourStationVisits.repository';
import { DbTimestampType } from '../types';
import { DayAssignments } from './DayAssignments.entity';
export class TourStationVisits {
[EntityRepositoryType]?: TourStationVisitsRepository;
[PrimaryKeyProp]?: ['assignment', 'station_key'];
assignment!: Ref<DayAssignments>;
assignment_id!: number;
station_key!: string;
status!: TTourStationVisitsStatus;
updated_at!: string & Opt;
}
export const TourStationVisitsStatus = {
VISITED: 'visited',
SKIPPED: 'skipped',
} as const;
export type TTourStationVisitsStatus = (typeof TourStationVisitsStatus)[keyof typeof TourStationVisitsStatus];
export const TourStationVisitsSchema = defineEntity({
class: TourStationVisits,
repository: () => TourStationVisitsRepository,
uniques: [{ properties: ['assignment', 'station_key'] }],
properties: {
assignment: () => p.manyToOne(DayAssignments).primary().ref().deleteRule('cascade').hidden(),
assignment_id: p.integer().persist(false),
station_key: p.text().primary(),
status: p.enum(() => TourStationVisitsStatus),
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -17,8 +17,21 @@ export class TourWaypoints {
shaping: number & Opt = 0;
linkedPlace?: Ref<Places> | null;
linked_place_id?: number | null;
station_key?: string | null;
name?: string | null;
stay_minutes?: number | null;
importance?: TTourWaypointsImportance | null;
protected: number & Opt = 0;
opening_hours?: string | null;
}
export const TourWaypointsImportance = {
OPTIONAL: 'optional',
MUST: 'must',
} as const;
export type TTourWaypointsImportance = (typeof TourWaypointsImportance)[keyof typeof TourWaypointsImportance];
export const TourWaypointsSchema = defineEntity({
class: TourWaypoints,
repository: () => TourWaypointsRepository,
@@ -31,6 +44,11 @@ export const TourWaypointsSchema = defineEntity({
],
uniques: [{ properties: ['place', 'sequence'] }],
checks: [
{ name: 'tour_waypoints_protected_check', expression: 'protected IN (0, 1)' },
{
name: 'tour_waypoints_stay_minutes_check',
expression: 'stay_minutes IS NULL OR (stay_minutes >= 0 AND stay_minutes <= 1440)',
},
{ name: 'tour_waypoints_shaping_check', expression: 'shaping IN (0, 1)' },
],
properties: {
@@ -46,5 +64,11 @@ export const TourWaypointsSchema = defineEntity({
shaping: p.integer().default(0),
linkedPlace: () => p.manyToOne(Places).ref().nullable().hidden(),
linked_place_id: p.integer().nullable().persist(false),
station_key: p.text().nullable(),
name: p.text().nullable(),
stay_minutes: p.integer().nullable(),
importance: p.enum(() => TourWaypointsImportance).nullable(),
protected: p.integer().default(0),
opening_hours: p.text().nullable(),
},
});
+2
View File
@@ -109,6 +109,7 @@ import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
import { TodoItemsSchema } from './TodoItems.entity';
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
import { TourSourcesSchema } from './TourSources.entity';
import { TourStationVisitsSchema } from './TourStationVisits.entity';
import { TourTypesSchema } from './TourTypes.entity';
import { TourWaypointsSchema } from './TourWaypoints.entity';
import { ToursSchema } from './Tours.entity';
@@ -253,6 +254,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TodoItemsSchema,
TourObstacleReviewsSchema,
TourSourcesSchema,
TourStationVisitsSchema,
TourTypesSchema,
TourWaypointsSchema,
ToursSchema,
@@ -0,0 +1,10 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface TourStationVisitsTable {
assignment_id: number;
station_key: string;
status: string;
updated_at: InsertOptional<string>;
}
@@ -13,4 +13,10 @@ export interface TourWaypointsTable {
lock: InsertOptional<string | null>;
shaping: InsertOptional<number>;
linked_place_id: InsertOptional<number | null>;
station_key: InsertOptional<string | null>;
name: InsertOptional<string | null>;
stay_minutes: InsertOptional<number | null>;
importance: InsertOptional<string | null>;
protected: InsertOptional<number>;
opening_hours: InsertOptional<string | null>;
}
+2
View File
@@ -115,6 +115,7 @@ import type { TodoCategoryAssigneesTable } from './TodoCategoryAssignees.table';
import type { TodoItemsTable } from './TodoItems.table';
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
import type { TourSourcesTable } from './TourSources.table';
import type { TourStationVisitsTable } from './TourStationVisits.table';
import type { TourTypesTable } from './TourTypes.table';
import type { TourWaypointsTable } from './TourWaypoints.table';
import type { ToursTable } from './Tours.table';
@@ -265,6 +266,7 @@ export interface DB {
todo_items: TodoItemsTable;
tour_obstacle_reviews: TourObstacleReviewsTable;
tour_sources: TourSourcesTable;
tour_station_visits: TourStationVisitsTable;
tour_types: TourTypesTable;
tour_waypoints: TourWaypointsTable;
tours: ToursTable;
@@ -0,0 +1,42 @@
import { Migration } from '@mikro-orm/migrations';
/**
* CW-01 to CW-04, CW-10: a tour can be a city walk. The `walk` key has been in
* `tour_types`, disabled, since every contract type was seeded; it is switched
* on here. Its points are stations: each keeps a key across saves, a name,
* how long it is stayed at, how much it matters, whether a proposed change
* must leave it, and the opening hours it was found with. Every column is
* NULL (or off) on the points saved before, so no tour changes its meaning.
*
* How far a walk got on a day is kept per day assignment and station key, so
* the same walk on another day, or a copy, starts with nothing visited, and a
* visit goes with its assignment.
*/
export class Migration20200101045300_a_tour_can_be_a_city_walk extends Migration {
override name = 'Migration20200101045300_a_tour_can_be_a_city_walk';
override up(): void {
this.addSql('ALTER TABLE tour_waypoints ADD COLUMN station_key TEXT');
this.addSql('ALTER TABLE tour_waypoints ADD COLUMN name TEXT');
this.addSql(
'ALTER TABLE tour_waypoints ADD COLUMN stay_minutes INTEGER CHECK (stay_minutes IS NULL OR (stay_minutes >= 0 AND stay_minutes <= 1440))',
);
this.addSql(
"ALTER TABLE tour_waypoints ADD COLUMN importance TEXT CHECK (importance IS NULL OR importance IN ('optional', 'must'))",
);
this.addSql(
'ALTER TABLE tour_waypoints ADD COLUMN protected INTEGER NOT NULL DEFAULT 0 CHECK (protected IN (0, 1))',
);
this.addSql('ALTER TABLE tour_waypoints ADD COLUMN opening_hours TEXT');
this.addSql(`
CREATE TABLE tour_station_visits (
assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
station_key TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('visited', 'skipped')),
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (assignment_id, station_key)
)
`);
this.addSql("UPDATE tour_types SET enabled = 1 WHERE key = 'walk'");
}
}
@@ -0,0 +1,112 @@
import type { TourStationVisits, TTourStationVisitsStatus } from '../entities/TourStationVisits.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** `status` narrowed to the two values the column's CHECK constraint allows. */
type VisitsDB = {
tour_station_visits: Omit<DB['tour_station_visits'], 'status'> & { status: TTourStationVisitsStatus };
day_assignments: DB['day_assignments'];
days: DB['days'];
};
/** One station of a city walk visited or skipped on one of its days. */
export interface TourStationVisitRow {
assignment_id: number;
station_key: string;
status: TTourStationVisitsStatus;
}
/**
* `tour_station_visits` (CW-03): how far a city walk got on a day, per day
* assignment and station key. A station without a row is still planned; a
* visit goes with its assignment.
*/
export class TourStationVisitsRepository extends TrekRepository<TourStationVisits> {
private db() {
return this.kysely<VisitsDB>();
}
/** A day assignment of this trip: the place it puts on which day; undefined for one of another trip or none. */
async assignmentInTrip(
assignment_id: number,
trip_id: number,
): Promise<{ place_id: number; day_id: number } | undefined> {
return await this.db()
.selectFrom('day_assignments as da')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select(['da.place_id', 'da.day_id'])
.where('da.id', '=', assignment_id)
.where('d.trip_id', '=', trip_id)
.executeTakeFirst();
}
/** The assignment that puts this place on this day of this trip; undefined where there is none. */
async assignmentOnDay(trip_id: number, place_id: number, day_id: number): Promise<number | undefined> {
const row = await this.db()
.selectFrom('day_assignments as da')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select('da.id')
.where('da.place_id', '=', place_id)
.where('da.day_id', '=', day_id)
.where('d.trip_id', '=', trip_id)
.executeTakeFirst();
return row?.id;
}
/** Every visit on the days of one trip, for its day plan. */
async listForTrip(trip_id: number): Promise<TourStationVisitRow[]> {
return await this.db()
.selectFrom('tour_station_visits as v')
.innerJoin('day_assignments as da', 'da.id', 'v.assignment_id')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select(['v.assignment_id', 'v.station_key', 'v.status'])
.where('d.trip_id', '=', trip_id)
.orderBy('v.assignment_id', 'asc')
.orderBy('v.station_key', 'asc')
.execute();
}
/** The visits of one day assignment. */
async listForAssignment(assignment_id: number): Promise<TourStationVisitRow[]> {
return await this.db()
.selectFrom('tour_station_visits as v')
.select(['v.assignment_id', 'v.station_key', 'v.status'])
.where('v.assignment_id', '=', assignment_id)
.orderBy('v.station_key', 'asc')
.execute();
}
/** Marks a station visited or skipped on that day, replacing what it was. */
async set(assignment_id: number, station_key: string, status: TTourStationVisitsStatus): Promise<void> {
await this.db()
.insertInto('tour_station_visits')
.values({ assignment_id, station_key, status })
.onConflict((oc) =>
oc.columns(['assignment_id', 'station_key']).doUpdateSet((eb) => ({
status: eb.ref('excluded.status'),
updated_at: eb.fn<string>('CURRENT_TIMESTAMP', []),
}))
)
.execute();
}
/** Takes a station back to planned on that day. */
async clear(assignment_id: number, station_key: string): Promise<void> {
await this.db()
.deleteFrom('tour_station_visits')
.where('assignment_id', '=', assignment_id)
.where('station_key', '=', station_key)
.execute();
}
/** Drops the visits of stations a walk no longer has, on every day it is on. */
async dropStationsNotIn(place_id: number, keep: readonly string[]): Promise<void> {
const assignments = this.db()
.selectFrom('day_assignments')
.select('id')
.where('place_id', '=', place_id);
let query = this.db().deleteFrom('tour_station_visits').where('assignment_id', 'in', assignments);
if (keep.length > 0) query = query.where('station_key', 'not in', [...keep]);
await query.execute();
}
}
@@ -1,5 +1,5 @@
import { decodeJson, encodeJson } from '../../utils/json-column';
import type { TourWaypoints } from '../entities/TourWaypoints.entity';
import type { TourWaypoints, TTourWaypointsImportance } from '../entities/TourWaypoints.entity';
import { TOUR_WAYPOINT_FIXED_LEG, TOUR_WAYPOINT_LOCK } from '../json-columns';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
@@ -19,6 +19,18 @@ export interface TourWaypointRow {
shaping?: boolean;
/** PR1-10: the place of the trip this point stands for; absent for a free point. */
linked_place_id?: number | null;
/** CW-03: the point's key, the same across saves; absent on a point saved before keys. */
key?: string;
/** The point's own name; absent where it has none. */
name?: string | null;
/** CW-02: a city walk station's stay; absent where it is not known, 0 for a point passed through. */
stay_minutes?: number | null;
/** CW-03: how much a station matters; absent for normal. */
importance?: TTourWaypointsImportance | null;
/** CW-10: a station a proposed change keeps; absent when it is not protected. */
protected?: boolean;
/** CW-04: the station's opening hours as OpenStreetMap writes them; absent where there are none. */
opening_hours?: string | null;
}
/** The row as stored, the fixed leg still JSON text. */
@@ -31,18 +43,52 @@ interface StoredWaypoint {
lock: string | null;
shaping: number;
linked_place_id: number | null;
station_key: string | null;
name: string | null;
stay_minutes: number | null;
importance: TTourWaypointsImportance | null;
protected: number;
opening_hours: string | null;
}
/** A stored row as callers read it: the fixed leg, the lock and the shaping flag, each left out entirely where there is none. */
function readWaypoint({ fixed_leg, lock, shaping, linked_place_id, ...point }: StoredWaypoint): TourWaypointRow {
/** The columns a waypoint is read with, as the stored row names them. */
const WAYPOINT_COLUMNS = [
'lat',
'lng',
'role',
'sequence',
'fixed_leg',
'lock',
'shaping',
'linked_place_id',
'station_key',
'name',
'stay_minutes',
'importance',
'protected',
'opening_hours',
] as const;
/** A stored row as callers read it: every optional part left out entirely where there is none. */
function readWaypoint(row: StoredWaypoint): TourWaypointRow {
const { fixed_leg, lock, shaping, linked_place_id, station_key, name, stay_minutes, importance, opening_hours } = row;
const leg = decodeJson(TOUR_WAYPOINT_FIXED_LEG, fixed_leg, 'tour waypoint');
const stop = decodeJson(TOUR_WAYPOINT_LOCK, lock, 'tour waypoint');
return {
...point,
lat: row.lat,
lng: row.lng,
role: row.role,
sequence: row.sequence,
...(leg ? { fixed_leg: leg } : {}),
...(stop ? { lock: stop } : {}),
...(shaping ? { shaping: true } : {}),
...(linked_place_id != null ? { linked_place_id } : {}),
...(station_key ? { key: station_key } : {}),
...(name ? { name } : {}),
...(stay_minutes != null ? { stay_minutes } : {}),
...(importance ? { importance } : {}),
...(row.protected ? { protected: true } : {}),
...(opening_hours ? { opening_hours } : {}),
};
}
@@ -51,9 +97,12 @@ export interface TourWaypointWithPlaceRow extends TourWaypointRow {
place_id: number;
}
/** `role` narrowed to the three values the column's CHECK constraint allows. */
/** `role` and `importance` narrowed to the values the columns' CHECK constraints allow. */
type TourWaypointsKyselyDB = Pick<DB, 'places' | 'tours'> & {
tour_waypoints: Omit<DB['tour_waypoints'], 'role'> & { role: TourWaypointRow['role'] };
tour_waypoints: Omit<DB['tour_waypoints'], 'role' | 'importance'> & {
role: TourWaypointRow['role'];
importance: TTourWaypointsImportance | null;
};
};
/**
@@ -70,7 +119,7 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
async listForPlace(place_id: number): Promise<TourWaypointRow[]> {
const rows = await this.db()
.selectFrom('tour_waypoints')
.select(['lat', 'lng', 'role', 'sequence', 'fixed_leg', 'lock', 'shaping', 'linked_place_id'])
.select(WAYPOINT_COLUMNS)
.where('place_id', '=', place_id)
.orderBy('sequence', 'asc')
.execute();
@@ -82,17 +131,7 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
const rows = await this.db()
.selectFrom('tour_waypoints as tw')
.innerJoin('places as p', 'p.id', 'tw.place_id')
.select([
'tw.place_id',
'tw.lat',
'tw.lng',
'tw.role',
'tw.sequence',
'tw.fixed_leg',
'tw.lock',
'tw.shaping',
'tw.linked_place_id',
])
.select(['tw.place_id', ...WAYPOINT_COLUMNS.map((column) => `tw.${column}` as const)])
.where('p.trip_id', '=', trip_id)
.orderBy('tw.place_id', 'asc')
.orderBy('tw.sequence', 'asc')
@@ -126,6 +165,12 @@ export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
lock: w.lock ? encodeJson(TOUR_WAYPOINT_LOCK, w.lock) : null,
shaping: w.shaping ? 1 : 0,
linkedPlace: linkOf(w.linked_place_id),
station_key: w.key ?? null,
name: w.name ?? null,
stay_minutes: w.stay_minutes ?? null,
importance: w.importance ?? null,
protected: w.protected ? 1 : 0,
opening_hours: w.opening_hours ?? null,
})),
);
}
+11 -1
View File
@@ -44,6 +44,8 @@ export interface TourListRow {
revision: number;
/** MF-08: a hike's routing preferences, still JSON text. */
hiking_preferences: string | null;
/** CW-03: the points that are no shaping points, the stations of a city walk. */
station_count: number;
}
/** LIB-02: a tour of another trip as the take-over list reads it, with the trip it is in. */
@@ -255,6 +257,12 @@ export class ToursRepository extends TrekRepository<Tours> {
eb
.exists(eb.selectFrom('tour_waypoints as tw').select('tw.id').whereRef('tw.place_id', '=', 'p.id'))
.as('has_waypoints'),
eb
.selectFrom('tour_waypoints as sw')
.select((sub) => sub.fn.countAll<number>().as('n'))
.whereRef('sw.place_id', '=', 'p.id')
.where('sw.shaping', '=', 0)
.as('station_count'),
]);
}
@@ -780,10 +788,11 @@ function toLibraryRow<R extends Omit<TourLibraryRow, 'has_waypoints'> & { has_wa
}
function toListRow<
R extends Omit<TourListRow, 'planned' | 'has_waypoints' | 'has_recorded_track'> & {
R extends Omit<TourListRow, 'planned' | 'has_waypoints' | 'has_recorded_track' | 'station_count'> & {
planned: unknown;
has_waypoints: unknown;
has_recorded_track: unknown;
station_count: unknown;
},
>(r: R): TourListRow {
return {
@@ -791,5 +800,6 @@ function toListRow<
planned: Number(r.planned),
has_waypoints: Number(r.has_waypoints),
has_recorded_track: Number(r.has_recorded_track),
station_count: Number(r.station_count ?? 0),
};
}