230 lines
11 KiB
JavaScript
230 lines
11 KiB
JavaScript
// Les événements métier : la seule donnée stockée (ADR 0006). Leur format est un
|
||
// contrat durable, décrit dans docs/evenements.md : toute évolution passe par une
|
||
// nouvelle version `v` et une migration testée.
|
||
// Glossaire : docs/glossaire/evenement.md
|
||
|
||
import { wodResultProblem } from "./wod.js";
|
||
import { randomId } from "./ids.js";
|
||
import { validateProgram } from "./program.js";
|
||
import { validateProfile } from "./profile.js";
|
||
import { EFFORTS, MODES, PROGRAM_SOURCES, SESSION_KINDS, TRACKING_MODES, LOCK_KINDS } from "./vocabulary.js";
|
||
|
||
/** Version courante du format, pour tous les types. */
|
||
export const EVENT_VERSION = 1;
|
||
|
||
/**
|
||
* Enveloppe commune.
|
||
* @template {string} T
|
||
* @template D
|
||
* @typedef {object} Envelope
|
||
* @property {string} id unique ; aléatoire, ou déterministe pour un import
|
||
* @property {string} at date et heure ISO 8601 UTC de l'enregistrement
|
||
* @property {string} device identifiant de l'appareil (ou de la source) qui l'a créé
|
||
* @property {number} v
|
||
* @property {T} type
|
||
* @property {D} data
|
||
*/
|
||
|
||
/**
|
||
* Série faite. `reps` ou `effort` peuvent manquer pour une séance saisie a posteriori.
|
||
* Une série faite. `kg` : sa charge, quand chaque série a la sienne (charge par série,
|
||
* glossaire : docs/glossaire/charge-par-serie.md) ; omis, la charge est le `loadKg` de l'exercice.
|
||
* @typedef {{reps: number|null, effort: import("./vocabulary.js").Effort|null, kg?: number}} LoggedSet
|
||
*/
|
||
|
||
/**
|
||
* @typedef {object} LoggedExercise
|
||
* @property {string} id clé stable de l'exercice (ref, sinon nom)
|
||
* @property {string} name
|
||
* @property {string} target objectif du jour, lisible : « 4 × 8 », « 3 × 40 s »
|
||
* @property {import("./vocabulary.js").TrackingMode} tracking
|
||
* @property {number|null} loadKg
|
||
* @property {number|null} seconds
|
||
* @property {number|null} plannedSets
|
||
* @property {LoggedSet[]} sets séries faites, dans l'ordre
|
||
* @property {string} [replaces] id de l'exercice prévu, s'il a été remplacé pour cette séance
|
||
*/
|
||
|
||
/**
|
||
* Contenu d'une séance faite. Glossaire : docs/glossaire/seance.md
|
||
* @typedef {object} SessionData
|
||
* @property {string} date jour local AAAA-MM-JJ où la séance a été faite
|
||
* @property {import("./vocabulary.js").SessionKind} kind
|
||
* @property {string} ref clé de séance (« A »), nom du cardio, ou id d'activité
|
||
* @property {string} name
|
||
* @property {LoggedExercise[]} exercises vide pour un cardio ou une activité
|
||
* @property {{done: number, total: number}|null} warmup
|
||
* @property {import("./wod.js").WodResult} [wod] score d'une séance WOD (ADR 0010)
|
||
*/
|
||
|
||
/**
|
||
* @typedef {object} PlanSettings
|
||
* @property {number[]} days jours disponibles, 0 = lundi … 6 = dimanche
|
||
* @property {Record<string, string>} locks jour → « strength », « strength:A », « cardio:1 », « activity:id », « rest »
|
||
*/
|
||
|
||
/**
|
||
* @typedef {Envelope<"SessionLogged", SessionData>
|
||
* | Envelope<"SessionCorrected", {sessionId: string, session: SessionData}>
|
||
* | Envelope<"SessionDeleted", {sessionId: string}>
|
||
* | Envelope<"DaySkipped", {date: string}>
|
||
* | Envelope<"DayUnskipped", {date: string}>
|
||
* | Envelope<"WorkingLoadSet", {key: string, loadKg?: number|null, seconds?: number|null, setsKg?: number[]|null}>
|
||
* | Envelope<"TrackingModeSet", {key: string, mode: import("./vocabulary.js").TrackingMode|null}>
|
||
* | Envelope<"WeightRecorded", {date: string, kg: number}>
|
||
* | Envelope<"WeightDeleted", {date: string}>
|
||
* | Envelope<"ProgramProposed", {program: import("./program.js").Program, source: import("./vocabulary.js").ProgramSource, reason: string, profile?: import("./profile.js").Profile}>
|
||
* | Envelope<"ProgramAdopted", {program: import("./program.js").Program, source: import("./vocabulary.js").ProgramSource, reason?: string, proposalId?: string}>
|
||
* | Envelope<"ProposalRejected", {proposalId: string, reason?: string}>
|
||
* | Envelope<"ProfileUpdated", {profile: import("./profile.js").Profile}>
|
||
* | Envelope<"PlanSettingsChanged", PlanSettings & {week: string|null}>
|
||
* | Envelope<"ModeChanged", {mode: import("./vocabulary.js").Mode, reason?: string}>
|
||
* } DomainEvent
|
||
*/
|
||
|
||
/** @typedef {DomainEvent["type"]} EventType */
|
||
|
||
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||
const isDate = (/** @type {unknown} */ x) => typeof x === "string" && DATE.test(x) && !Number.isNaN(Date.parse(x));
|
||
const isText = (/** @type {unknown} */ x) => typeof x === "string" && x.trim() !== "";
|
||
const isNumOrNull = (/** @type {unknown} */ x) => x === null || (typeof x === "number" && Number.isFinite(x) && x >= 0);
|
||
const isLoad = (/** @type {unknown} */ x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x <= 1000;
|
||
const isObject = (/** @type {unknown} */ x) => typeof x === "object" && x !== null && !Array.isArray(x);
|
||
|
||
/**
|
||
* @param {any} s
|
||
* @returns {string|null}
|
||
*/
|
||
function sessionError(s) {
|
||
if (!isObject(s)) return "séance absente";
|
||
if (!isDate(s.date)) return "date de séance invalide (AAAA-MM-JJ)";
|
||
if (!SESSION_KINDS.includes(s.kind)) return "nature de séance inconnue";
|
||
if (!isText(s.ref) || !isText(s.name)) return "séance sans référence ou sans nom";
|
||
if (s.warmup !== null && !(isObject(s.warmup) && Number.isInteger(s.warmup.done) && Number.isInteger(s.warmup.total)))
|
||
return "échauffement mal formé";
|
||
if (s.wod !== undefined) {
|
||
const problem = wodResultProblem(s.wod);
|
||
if (problem) return problem;
|
||
}
|
||
if (!Array.isArray(s.exercises)) return "exercices absents";
|
||
for (const x of s.exercises) {
|
||
if (!isObject(x) || !isText(x.id) || !isText(x.name) || typeof x.target !== "string") return "exercice mal formé";
|
||
if (!TRACKING_MODES.includes(x.tracking)) return "mode de suivi inconnu";
|
||
if (!isNumOrNull(x.loadKg) || !isNumOrNull(x.seconds) || !(x.plannedSets === null || Number.isInteger(x.plannedSets)))
|
||
return "charge, durée ou séries prévues invalides";
|
||
if (x.replaces !== undefined && !isText(x.replaces)) return "exercice remplacé mal formé";
|
||
if (!Array.isArray(x.sets)) return "séries absentes";
|
||
for (const set of x.sets)
|
||
if (!isObject(set) || !isNumOrNull(set.reps) || !(set.effort === null || EFFORTS.includes(set.effort))
|
||
|| (set.kg !== undefined && !isLoad(set.kg))) return "série mal formée";
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** @type {Record<EventType, (data: any) => string|null>} */
|
||
const DATA_CHECKS = {
|
||
SessionLogged: (d) => sessionError(d),
|
||
SessionCorrected: (d) => (isText(d.sessionId) ? sessionError(d.session) : "sessionId manquant"),
|
||
SessionDeleted: (d) => (isText(d.sessionId) ? null : "sessionId manquant"),
|
||
DaySkipped: (d) => (isDate(d.date) ? null : "date invalide"),
|
||
DayUnskipped: (d) => (isDate(d.date) ? null : "date invalide"),
|
||
WorkingLoadSet: (d) =>
|
||
!isText(d.key) ? "clé manquante"
|
||
: ("loadKg" in d && !isNumOrNull(d.loadKg)) || ("seconds" in d && !isNumOrNull(d.seconds)) ? "valeur invalide"
|
||
: "setsKg" in d && !(d.setsKg === null || (Array.isArray(d.setsKg) && d.setsKg.length >= 1 && d.setsKg.length <= 12 && d.setsKg.every(isLoad))) ? "charges par série invalides"
|
||
: !("loadKg" in d) && !("seconds" in d) ? "ni charge ni durée"
|
||
: null,
|
||
TrackingModeSet: (d) => (!isText(d.key) ? "clé manquante" : d.mode === null || TRACKING_MODES.includes(d.mode) ? null : "mode inconnu"),
|
||
WeightRecorded: (d) => (!isDate(d.date) ? "date invalide" : typeof d.kg === "number" && d.kg >= 20 && d.kg <= 400 ? null : "poids invalide"),
|
||
WeightDeleted: (d) => (isDate(d.date) ? null : "date invalide"),
|
||
ProgramProposed: (d) =>
|
||
!PROGRAM_SOURCES.includes(d.source) ? "source inconnue"
|
||
: typeof d.reason !== "string" ? "raison manquante"
|
||
: d.profile !== undefined && validateProfile(d.profile).length ? "profil proposé : " + validateProfile(d.profile)[0]
|
||
: validateProgram(d.program)[0] ?? null,
|
||
ProgramAdopted: (d) =>
|
||
!PROGRAM_SOURCES.includes(d.source) ? "source inconnue"
|
||
: d.proposalId !== undefined && !isText(d.proposalId) ? "proposalId invalide"
|
||
: validateProgram(d.program)[0] ?? null,
|
||
ProposalRejected: (d) => (isText(d.proposalId) ? null : "proposalId manquant"),
|
||
ProfileUpdated: (d) => validateProfile(d.profile)[0] ?? null,
|
||
PlanSettingsChanged: (d) => {
|
||
if (d.week !== null && !isDate(d.week)) return "semaine invalide";
|
||
if (!Array.isArray(d.days) || !d.days.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 0 && /** @type {number} */ (x) <= 6))
|
||
return "jours invalides";
|
||
if (!isObject(d.locks)) return "jours imposés invalides";
|
||
for (const [day, lock] of Object.entries(d.locks))
|
||
if (!/^[0-6]$/.test(day) || typeof lock !== "string" || !LOCK_KINDS.includes(/** @type {any} */ (lock.split(":")[0])))
|
||
return "jour imposé invalide";
|
||
return null;
|
||
},
|
||
ModeChanged: (d) => (MODES.includes(d.mode) ? null : "mode inconnu"),
|
||
};
|
||
|
||
/** Tous les types connus. */
|
||
export const EVENT_TYPES = /** @type {EventType[]} */ (Object.keys(DATA_CHECKS));
|
||
|
||
/**
|
||
* Vérifie un événement venu de l'extérieur (stockage, import, relais).
|
||
* @param {unknown} event
|
||
* @returns {string|null} le problème, ou null s'il est valide
|
||
*/
|
||
export function validateEvent(event) {
|
||
if (!isObject(event)) return "l'événement doit être un objet";
|
||
const e = /** @type {Record<string, any>} */ (event);
|
||
if (!isText(e.id) || !isText(e.device)) return "id ou device manquant";
|
||
if (typeof e.at !== "string" || Number.isNaN(Date.parse(e.at))) return "date 'at' invalide";
|
||
if (e.v !== EVENT_VERSION) return `version ${e.v} non prise en charge`;
|
||
const check = DATA_CHECKS[/** @type {EventType} */ (e.type)];
|
||
if (!check) return `type inconnu « ${e.type} »`;
|
||
if (!isObject(e.data)) return "data manquant";
|
||
const problem = check(e.data);
|
||
return problem ? `${e.type} : ${problem}` : null;
|
||
}
|
||
|
||
/**
|
||
* Crée un événement. Lève une erreur s'il est invalide : un événement mal formé
|
||
* ne doit jamais entrer dans le journal.
|
||
* @template {EventType} T
|
||
* @param {T} type
|
||
* @param {Extract<DomainEvent, {type: T}>["data"]} data
|
||
* @param {{device: string, at?: string, id?: string}} meta
|
||
* @returns {Extract<DomainEvent, {type: T}>}
|
||
*/
|
||
export function createEvent(type, data, meta) {
|
||
const event = /** @type {any} */ ({
|
||
id: meta.id ?? randomId(),
|
||
at: meta.at ?? new Date().toISOString(),
|
||
device: meta.device,
|
||
v: EVENT_VERSION,
|
||
type,
|
||
data,
|
||
});
|
||
const problem = validateEvent(event);
|
||
if (problem) throw new Error("Événement invalide : " + problem);
|
||
return event;
|
||
}
|
||
|
||
/**
|
||
* Ordre canonique du journal : par date, puis appareil, puis identifiant. Tous les
|
||
* appareils obtiennent ainsi le même état à partir des mêmes événements.
|
||
* @param {DomainEvent} a
|
||
* @param {DomainEvent} b
|
||
*/
|
||
export function compareEvents(a, b) {
|
||
return a.at < b.at ? -1 : a.at > b.at ? 1 : a.device < b.device ? -1 : a.device > b.device ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
||
}
|
||
|
||
/**
|
||
* Fusion par union (ADR 0006) : les événements sont immuables et identifiés,
|
||
* on garde le premier vu pour chaque id.
|
||
* @param {DomainEvent[]} a
|
||
* @param {DomainEvent[]} b
|
||
* @returns {DomainEvent[]} journal trié
|
||
*/
|
||
export function mergeLogs(a, b) {
|
||
const byId = new Map();
|
||
for (const e of [...a, ...b]) if (!byId.has(e.id)) byId.set(e.id, e);
|
||
return [...byId.values()].sort(compareEvents);
|
||
}
|