Proposition {program, profile?, reason} validée, erreurs en français.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
467 lines
24 KiB
JavaScript
467 lines
24 KiB
JavaScript
// Conversion des données d'Atelier, le prototype d'origine (reference/atelier/), en
|
||
// événements IA-Fit (ADR 0006, point 5). Trois formes sont acceptées :
|
||
// (a) l'état brut du serveur ou du localStorage d'Atelier
|
||
// {program, history, kg, plan, planNext, skips, suivi, poids, mode, journal} ;
|
||
// (b) le fichier exporté « pour LLM »
|
||
// {instructions, planning, program, charges_courantes, suivi_personnalise,
|
||
// poids_corporel, seances_manquees, history} ;
|
||
// (c) un programme seul {name, sessions…}.
|
||
// Les identifiants sont stables (stableId) : convertir deux fois le même fichier
|
||
// donne les mêmes événements, que la fusion par union dédoublonne.
|
||
|
||
import { createEvent } from "./events.js";
|
||
import { ATELIER_REFS, EXERCISES } from "./exercises.js";
|
||
import { stableId } from "./ids.js";
|
||
import { resolveExercise, trackingFor, validateProgram } from "./program.js";
|
||
import { DEFAULT_PROFILE } from "./profile.js";
|
||
|
||
/** @typedef {import("./events.js").DomainEvent} DomainEvent */
|
||
/** @typedef {import("./program.js").Program} Program */
|
||
/** @typedef {import("./program.js").ProgramExercise} ProgramExercise */
|
||
/** @typedef {import("./vocabulary.js").TrackingMode} TrackingMode */
|
||
|
||
/** @type {Record<string, TrackingMode>} */
|
||
const TRACKING = { charge: "load", temps: "time", "temps+charge": "time+load", aucun: "none" };
|
||
/** @type {Record<string, import("./vocabulary.js").Effort>} */
|
||
const EFFORT = { facile: "easy", correct: "ok", dur: "hard", echec: "failure" };
|
||
/** @type {Record<string, import("./vocabulary.js").Zone>} */
|
||
const ZONE = { bas: "lower", haut: "upper", tronc: "core", cardio: "cardio" };
|
||
/** @type {Record<string, import("./vocabulary.js").Intensity>} */
|
||
const INTENSITY = { legere: "light", moderee: "moderate", forte: "hard" };
|
||
/** @type {Record<string, import("./vocabulary.js").Mode>} */
|
||
const MODE = { progression: "progression", maintien: "maintenance", recuperation: "recovery" };
|
||
/** @type {Record<string, string>} */
|
||
const LOCK = { force: "strength", repos: "rest", activite: "activity", cardio: "cardio" };
|
||
|
||
/**
|
||
* Profil écrit en dur dans le serveur d'Atelier (server.js, get_user_constraints) :
|
||
* Atelier n'avait qu'un utilisateur. Repris pour l'état brut, qui n'en porte pas.
|
||
* @type {import("./profile.js").Profile}
|
||
*/
|
||
const ATELIER_SERVER_PROFILE = {
|
||
goal: "Ancrer l'habitude, perdre du gras, garder du muscle.",
|
||
context: "Revient d'une pratique en salle, s'entraîne 100 % à la maison.",
|
||
equipment: ["banc", "barre olympique et disques", "haltères", "élastiques sans point d'ancrage",
|
||
"corde à sauter", "tapis", "vélo, marche et course en extérieur"],
|
||
constraints: [
|
||
"Pas de pareur : rester loin de l'échec au développé couché et au squat.",
|
||
"Une seule barre : éviter de coupler deux exercices à la barre à des charges différentes.",
|
||
"Poids de corps encore élevé : privilégier vélo et marche, limiter les impacts répétés.",
|
||
"Une séance doit tenir en 45 à 55 minutes.",
|
||
],
|
||
heightCm: 170,
|
||
sessionMinutes: 50,
|
||
};
|
||
|
||
const isObject = (/** @type {unknown} */ x) => typeof x === "object" && x !== null && !Array.isArray(x);
|
||
const isText = (/** @type {unknown} */ x) => typeof x === "string" && x.trim() !== "";
|
||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||
/** Jour AAAA-MM-JJ valide en tête d'un texte, ou null. @param {unknown} x */
|
||
const dayOf = (x) => {
|
||
const d = typeof x === "string" ? x.slice(0, 10) : "";
|
||
return DAY.test(d) && !Number.isNaN(Date.parse(d)) ? d : null;
|
||
};
|
||
/** Nombre positif ou nul, depuis un nombre ou un texte (« 62,5 »), sinon null. @param {unknown} x */
|
||
const toNumber = (x) => {
|
||
if (typeof x === "string") x = x.trim() === "" ? NaN : Number(x.trim().replace(",", "."));
|
||
return typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : null;
|
||
};
|
||
/** @param {number} n @param {string} one @param {string} many */
|
||
const plural = (n, one, many) => `${n} ${n > 1 ? many : one}`;
|
||
|
||
/**
|
||
* Reconnaît un objet venu d'Atelier (formes a, b ou c), sans le valider.
|
||
* @param {unknown} obj
|
||
*/
|
||
export function looksLikeAtelier(obj) {
|
||
if (!isObject(obj)) return false;
|
||
const o = /** @type {Record<string, any>} */ (obj);
|
||
if (isObject(o.etat)) return true;
|
||
const markers = ["history", "kg", "plan", "planNext", "skips", "suivi", "poids", "journal",
|
||
"instructions", "planning", "charges_courantes", "suivi_personnalise", "poids_corporel", "seances_manquees"];
|
||
if (isObject(o.program) && markers.some((k) => k in o)) return true;
|
||
return Array.isArray(o.sessions) && looksLikeAtelierProgram(o);
|
||
}
|
||
|
||
/** @param {Record<string, any>} p */
|
||
function looksLikeAtelierProgram(p) {
|
||
if ("sub" in p || "activites" in p || "version" in p) return true;
|
||
return p.sessions.some((/** @type {any} */ s) => isObject(s) && ("sub" in s || (Array.isArray(s.exercises) &&
|
||
s.exercises.some((/** @type {any} */ e) => isObject(e) && ("bad" in e || "groupe" in e || "suivi" in e ||
|
||
(typeof e.ref === "string" && e.ref in ATELIER_REFS && !(e.ref in EXERCISES)))))));
|
||
}
|
||
|
||
/**
|
||
* Convertit des données d'Atelier en événements IA-Fit valides.
|
||
* @param {unknown} input objet déjà lu (JSON.parse)
|
||
* @param {{device: string, now?: Date}} options
|
||
* @returns {{events: DomainEvent[], report: string[]}}
|
||
*/
|
||
export function convertAtelier(input, { device, now = new Date() }) {
|
||
if (!isObject(input)) throw new Error("Le fichier d'Atelier doit contenir un objet JSON.");
|
||
let obj = /** @type {Record<string, any>} */ (input);
|
||
if (isObject(obj.etat)) obj = obj.etat; // réponse de GET /api/state
|
||
const at = now.toISOString();
|
||
/** @type {DomainEvent[]} */
|
||
const events = [];
|
||
/** @type {string[]} */
|
||
const report = [];
|
||
/** @type {string[]} */
|
||
const ignored = [];
|
||
/**
|
||
* @template {import("./events.js").EventType} T
|
||
* @param {T} type
|
||
* @param {Extract<DomainEvent, {type: T}>["data"]} data
|
||
* @param {string} key contenu canonique qui fixe l'identifiant
|
||
* @param {string} [when]
|
||
*/
|
||
const add = (type, data, key, when = at) =>
|
||
events.push(createEvent(type, /** @type {any} */ (data), { device, at: when, id: stableId("atelier", type + "|" + key) }));
|
||
|
||
const isExport = "instructions" in obj || "charges_courantes" in obj || "planning" in obj;
|
||
const isProgramOnly = !isObject(obj.program) && Array.isArray(obj.sessions);
|
||
const rawProgram = isProgramOnly ? obj : isObject(obj.program) ? obj.program : null;
|
||
|
||
// --- Programme ---
|
||
const conv = rawProgram ? convertProgram(rawProgram) : null;
|
||
if (!conv) ignored.push("aucun programme dans le fichier");
|
||
else {
|
||
const problems = validateProgram(conv.program);
|
||
if (problems.length) {
|
||
report.push(`Programme ignoré, invalide : ${problems.join(" ; ")}`);
|
||
} else {
|
||
add("ProgramAdopted", { program: conv.program, source: "atelier", reason: "Repris d'Atelier" }, JSON.stringify(conv.program));
|
||
const n = conv.program.sessions.reduce((s, x) => s + x.exercises.length, 0);
|
||
report.push(`Programme « ${conv.program.name} » : ${plural(conv.program.sessions.length, "séance", "séances")}, ${plural(n, "exercice", "exercices")}` +
|
||
(conv.program.activities?.length ? `, ${plural(conv.program.activities.length, "activité", "activités")}` : "") + ".");
|
||
}
|
||
report.push(...conv.notes);
|
||
}
|
||
if (isProgramOnly) return { events, report };
|
||
|
||
/** Exercice du programme et identifiant IA-Fit, pour une clé d'Atelier « A-rdl ». */
|
||
const lookup = (/** @type {string} */ atelierKey) => {
|
||
const dash = atelierKey.indexOf("-");
|
||
if (dash < 1) return null;
|
||
const session = atelierKey.slice(0, dash), base = atelierKey.slice(dash + 1);
|
||
const found = conv?.byAtelierKey.get(session + "|" + base);
|
||
return { session, item: found?.item ?? null, id: found?.id ?? ATELIER_REFS[/** @type {keyof typeof ATELIER_REFS} */ (base)] ?? base };
|
||
};
|
||
|
||
// --- Modes de suivi choisis (avant les charges : ils disent si une valeur est en secondes) ---
|
||
const rawTracking = isObject(obj.suivi) ? obj.suivi : isObject(obj.suivi_personnalise) ? obj.suivi_personnalise : {};
|
||
/** @type {Record<string, TrackingMode>} */
|
||
const overrides = {};
|
||
let trackingCount = 0;
|
||
for (const [k, v] of Object.entries(rawTracking)) {
|
||
const target = lookup(k), mode = TRACKING[v];
|
||
if (!target || !mode) { ignored.push(`mode de suivi « ${k} » = « ${v} »`); continue; }
|
||
const key = target.session + "-" + target.id;
|
||
overrides[key] = mode;
|
||
add("TrackingModeSet", { key, mode }, key + "|" + mode);
|
||
trackingCount++;
|
||
}
|
||
if (trackingCount) report.push(`${plural(trackingCount, "mode de suivi personnalisé", "modes de suivi personnalisés")}.`);
|
||
|
||
// --- Charges de travail ---
|
||
const rawLoads = isObject(obj.kg) ? obj.kg : isObject(obj.charges_courantes) ? obj.charges_courantes : {};
|
||
/** @type {Map<string, {loadKg?: number, seconds?: number}>} */
|
||
const loads = new Map();
|
||
let emptyLoads = 0;
|
||
for (const [k, v] of Object.entries(rawLoads)) {
|
||
const kgSuffix = k.endsWith("-kg");
|
||
const target = lookup(kgSuffix ? k.slice(0, -3) : k);
|
||
const value = toNumber(v);
|
||
if (!target) { ignored.push(`charge « ${k} » (clé illisible)`); continue; }
|
||
if (value === null) { emptyLoads++; continue; }
|
||
const key = target.session + "-" + target.id;
|
||
const mode = overrides[key] ?? (target.item ? trackingFor(target.item, undefined) : "load");
|
||
const entry = loads.get(key) ?? {};
|
||
if (!kgSuffix && (mode === "time" || mode === "time+load")) entry.seconds = value;
|
||
else entry.loadKg = value;
|
||
loads.set(key, entry);
|
||
}
|
||
for (const [key, entry] of loads) add("WorkingLoadSet", { key, ...entry }, key + "|" + JSON.stringify(entry));
|
||
if (loads.size) report.push(`${plural(loads.size, "charge de travail", "charges de travail")}.`);
|
||
if (emptyLoads) ignored.push(plural(emptyLoads, "valeur de charge vide", "valeurs de charge vides"));
|
||
|
||
// --- Historique ---
|
||
const history = Array.isArray(obj.history) ? obj.history : [];
|
||
/** @type {Map<string, number>} */
|
||
const occurrences = new Map();
|
||
const kinds = { strength: 0, cardio: 0, activity: 0 };
|
||
let badSessions = 0;
|
||
for (const entry of history) {
|
||
const session = isObject(entry) ? convertSession(entry, conv?.activityIds ?? new Map()) : null;
|
||
if (!session) { badSessions++; continue; }
|
||
const code = entry.session ?? entry.seance;
|
||
const base = session.date + "|" + code;
|
||
const n = (occurrences.get(base) ?? 0) + 1;
|
||
occurrences.set(base, n);
|
||
const when = typeof entry.date === "string" && entry.date.length > 10 && !Number.isNaN(Date.parse(entry.date))
|
||
? new Date(entry.date).toISOString() : session.date + "T12:00:00.000Z";
|
||
try {
|
||
add("SessionLogged", session, base + "|" + n, when);
|
||
kinds[session.kind]++;
|
||
} catch {
|
||
badSessions++;
|
||
}
|
||
}
|
||
const totalSessions = kinds.strength + kinds.cardio + kinds.activity;
|
||
if (totalSessions)
|
||
report.push(`${plural(totalSessions, "séance", "séances")} d'historique (${kinds.strength} de force, ${kinds.cardio} cardio, ${plural(kinds.activity, "activité", "activités")}).`);
|
||
if (badSessions) ignored.push(plural(badSessions, "séance illisible", "séances illisibles"));
|
||
|
||
// --- Planning ---
|
||
const plan = isObject(obj.plan) ? { days: obj.plan.days, locks: obj.plan.locks }
|
||
: isObject(obj.planning) ? { days: obj.planning.jours_disponibles, locks: obj.planning.jours_imposes } : null;
|
||
const toSettings = (/** @type {{days: unknown, locks: unknown}} */ p) => {
|
||
const days = Array.isArray(p.days) ? [...new Set(p.days.map(Number).filter((d) => Number.isInteger(d) && d >= 0 && d <= 6))].sort((a, b) => a - b) : [];
|
||
/** @type {Record<string, string>} */
|
||
const locks = {};
|
||
for (const [day, lock] of Object.entries(isObject(p.locks) ? /** @type {object} */ (p.locks) : {})) {
|
||
const converted = /^[0-6]$/.test(day) ? convertLock(lock, conv) : null;
|
||
if (converted) locks[day] = converted;
|
||
else ignored.push(`jour imposé « ${day} : ${lock} »`);
|
||
}
|
||
return { days, locks };
|
||
};
|
||
if (plan) {
|
||
const s = toSettings(plan);
|
||
add("PlanSettingsChanged", { week: null, ...s }, "default|" + JSON.stringify(s));
|
||
report.push(`Planning : ${plural(s.days.length, "jour disponible", "jours disponibles")}, ${plural(Object.keys(s.locks).length, "jour imposé", "jours imposés")}.`);
|
||
}
|
||
if (isObject(obj.planNext) && dayOf(obj.planNext.weekStart)) {
|
||
const week = /** @type {string} */ (dayOf(obj.planNext.weekStart));
|
||
const s = toSettings(obj.planNext);
|
||
add("PlanSettingsChanged", { week, ...s }, week + "|" + JSON.stringify(s));
|
||
report.push(`Réglages propres à la semaine du ${week}.`);
|
||
}
|
||
if (isObject(obj.plan) && Array.isArray(obj.plan.slots) || isObject(obj.planning) && obj.planning.semaine_en_cours)
|
||
ignored.push("créneaux de la semaine (le planning se recalcule)");
|
||
|
||
// --- Jours non faits ---
|
||
const rawSkips = isObject(obj.skips) ? Object.keys(obj.skips).filter((d) => obj.skips[d])
|
||
: Array.isArray(obj.seances_manquees) ? obj.seances_manquees : [];
|
||
const skips = [...new Set(rawSkips.map(dayOf).filter((d) => d !== null))].sort();
|
||
for (const date of skips) add("DaySkipped", { date }, date, date + "T12:00:00.000Z");
|
||
if (skips.length) report.push(`${plural(skips.length, "jour marqué non fait", "jours marqués non faits")}.`);
|
||
if (rawSkips.length > skips.length) ignored.push(plural(rawSkips.length - skips.length, "date de jour non fait illisible", "dates de jours non faits illisibles"));
|
||
|
||
// --- Pesées ---
|
||
const rawWeights = Array.isArray(obj.poids) ? obj.poids : Array.isArray(obj.poids_corporel) ? obj.poids_corporel : [];
|
||
/** @type {Map<string, number>} */
|
||
const weights = new Map();
|
||
for (const w of rawWeights) {
|
||
const date = isObject(w) ? dayOf(w.date) : null, kg = isObject(w) ? toNumber(w.kg) : null;
|
||
if (date && kg !== null && kg >= 20 && kg <= 400) weights.set(date, kg);
|
||
else ignored.push(`pesée ${JSON.stringify(w)}`);
|
||
}
|
||
for (const [date, kg] of [...weights].sort()) add("WeightRecorded", { date, kg }, date + "|" + kg, date + "T12:00:00.000Z");
|
||
if (weights.size) report.push(`${plural(weights.size, "pesée", "pesées")}.`);
|
||
|
||
// --- Mode ---
|
||
if (typeof obj.mode === "string") {
|
||
const mode = MODE[obj.mode];
|
||
if (!mode) ignored.push(`mode « ${obj.mode} »`);
|
||
else if (mode !== "progression") {
|
||
add("ModeChanged", { mode, reason: "Repris d'Atelier" }, mode);
|
||
report.push(`Mode : ${obj.mode}.`);
|
||
}
|
||
}
|
||
|
||
// --- Profil ---
|
||
if (isExport) {
|
||
const profile = profileFromInstructions(obj.instructions);
|
||
if (profile) {
|
||
add("ProfileUpdated", { profile }, JSON.stringify(profile));
|
||
report.push("Profil : objectif, contexte, matériel et contraintes repris des consignes du fichier ; à vérifier dans l'app.");
|
||
} else ignored.push("profil (consignes absentes du fichier)");
|
||
} else {
|
||
const profile = structuredClone(ATELIER_SERVER_PROFILE);
|
||
add("ProfileUpdated", { profile }, JSON.stringify(profile));
|
||
report.push("Profil : repris du profil écrit en dur dans Atelier (taille, matériel, contraintes) ; à vérifier dans l'app.");
|
||
}
|
||
|
||
// --- Ce qui n'a pas d'équivalent ---
|
||
if (Array.isArray(obj.journal) && obj.journal.length)
|
||
ignored.push(plural(obj.journal.length, "entrée du journal des outils de l'IA", "entrées du journal des outils de l'IA"));
|
||
if (isExport) ignored.push("consignes pour l'IA et résumé de l'historique (IA-Fit les recalcule)");
|
||
|
||
if (ignored.length) report.push("Ignoré : " + ignored.join(" ; ") + ".");
|
||
return { events, report };
|
||
}
|
||
|
||
/**
|
||
* Programme d'Atelier → programme IA-Fit, avec les correspondances utiles au reste
|
||
* de la conversion.
|
||
* @param {Record<string, any>} p
|
||
*/
|
||
function convertProgram(p) {
|
||
/** @type {string[]} */
|
||
const notes = [];
|
||
/** @type {Map<string, {item: ProgramExercise, id: string}>} clé « A|rdl » (session|ref ou nom d'Atelier) */
|
||
const byAtelierKey = new Map();
|
||
/** @type {Map<string, string>} id d'activité d'Atelier → id IA-Fit */
|
||
const activityIds = new Map();
|
||
/** @type {string[]} */
|
||
const unknownRefs = [];
|
||
|
||
/** @type {Program} */
|
||
const program = { name: isText(p.name) ? p.name : "Programme d'Atelier", sessions: [] };
|
||
if (isText(p.sub)) program.subtitle = p.sub;
|
||
for (const s of Array.isArray(p.sessions) ? p.sessions : []) {
|
||
if (!isObject(s)) continue;
|
||
/** @type {import("./program.js").ProgramSession} */
|
||
const session = { key: String(s.key ?? ""), name: String(s.name ?? ""), exercises: [] };
|
||
if (isText(s.sub)) session.subtitle = s.sub;
|
||
if (typeof s.color === "string" && /^#[0-9A-Fa-f]{6}$/.test(s.color)) session.color = s.color;
|
||
if (isText(s.tag)) session.tag = s.tag;
|
||
for (const e of Array.isArray(s.exercises) ? s.exercises : []) {
|
||
if (!isObject(e)) continue;
|
||
/** @type {ProgramExercise} */
|
||
const item = { sets: Number(e.sets), reps: String(e.reps ?? ""), rest: Number(e.rest) };
|
||
const ref = isText(e.ref) ? ATELIER_REFS[/** @type {keyof typeof ATELIER_REFS} */ (e.ref)] : undefined;
|
||
if (ref) item.ref = ref;
|
||
if (isText(e.name)) item.name = e.name;
|
||
else if (isText(e.ref) && !ref) item.name = e.ref;
|
||
if (isText(e.ref) && !ref) unknownRefs.push(`${e.ref} (gardé sous le nom « ${item.name} »)`);
|
||
if (Array.isArray(e.cues)) item.cues = e.cues.map(String);
|
||
if (Array.isArray(e.bad)) item.mistakes = e.bad.map(String);
|
||
if (isText(e.groupe)) item.group = e.groupe;
|
||
if (TRACKING[e.suivi]) item.tracking = TRACKING[e.suivi];
|
||
if (isText(e.note)) item.note = e.note;
|
||
session.exercises.push(item);
|
||
const atelierBase = isText(e.ref) ? e.ref : item.name ?? "";
|
||
byAtelierKey.set(session.key + "|" + atelierBase, { item, id: resolveExercise(item).id });
|
||
}
|
||
program.sessions.push(session);
|
||
}
|
||
if (unknownRefs.length) notes.push(`Références inconnues retirées : ${unknownRefs.join(", ")}.`);
|
||
|
||
if (Array.isArray(p.activites) && p.activites.length) {
|
||
program.activities = [];
|
||
for (const a of p.activites) {
|
||
if (!isObject(a)) continue;
|
||
const id = String(a.id ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 32) || "activite";
|
||
activityIds.set(String(a.id), id);
|
||
/** @type {import("./program.js").Activity} */
|
||
const activity = {
|
||
id, name: String(a.nom ?? id),
|
||
zones: (Array.isArray(a.sollicite) ? a.sollicite : []).map((/** @type {string} */ z) => ZONE[z]).filter(Boolean),
|
||
intensity: INTENSITY[a.intensite] ?? "moderate",
|
||
minutes: toNumber(a.duree) ?? 60,
|
||
};
|
||
if (typeof a.couleur === "string" && /^#[0-9A-Fa-f]{6}$/.test(a.couleur)) activity.color = a.couleur;
|
||
program.activities.push(activity);
|
||
}
|
||
}
|
||
/** Index des cardios qui occupent un jour, dans l'ordre d'Atelier (cardioSlots). */
|
||
const cardioSlots = [];
|
||
if (Array.isArray(p.cardio) && p.cardio.length) {
|
||
program.cardio = p.cardio.filter(isObject).map((/** @type {any} */ c, /** @type {number} */ i) => {
|
||
if (c.slot !== false) cardioSlots.push(i);
|
||
return { name: String(c.name ?? "Cardio"), inPlan: c.slot !== false, text: String(c.text ?? "") };
|
||
});
|
||
}
|
||
if (Array.isArray(p.rules) && p.rules.length)
|
||
program.rules = p.rules.filter(isObject).map((/** @type {any} */ r) => ({ name: String(r.name ?? ""), text: String(r.text ?? "") }));
|
||
return { program, notes, byAtelierKey, activityIds, cardioSlots };
|
||
}
|
||
|
||
/**
|
||
* Jour imposé d'Atelier (« force:A », « repos », « activite:foot », « cardio:1 ») →
|
||
* IA-Fit. Le n° d'un cardio d'Atelier compte les seuls cardios qui occupent un jour ;
|
||
* celui d'IA-Fit compte tous les cardios du programme.
|
||
* @param {unknown} lock
|
||
* @param {ReturnType<typeof convertProgram>|null} conv
|
||
* @returns {string|null}
|
||
*/
|
||
function convertLock(lock, conv) {
|
||
if (typeof lock !== "string") return null;
|
||
const [kind, ...rest] = lock.split(":");
|
||
const q = rest.join(":");
|
||
const target = LOCK[kind];
|
||
if (!target) return null;
|
||
if (!q) return target;
|
||
if (kind === "activite") return "activity:" + (conv?.activityIds.get(q) ?? q);
|
||
if (kind === "cardio") {
|
||
const index = conv?.cardioSlots[Number(q)];
|
||
return index === undefined ? (conv ? null : "cardio:" + q) : "cardio:" + index;
|
||
}
|
||
return target + ":" + q;
|
||
}
|
||
|
||
/**
|
||
* Entrée d'historique d'Atelier → séance IA-Fit (sans validation finale).
|
||
* @param {Record<string, any>} e
|
||
* @param {Map<string, string>} activityIds
|
||
* @returns {import("./events.js").SessionData|null}
|
||
*/
|
||
function convertSession(e, activityIds) {
|
||
const date = dayOf(e.date);
|
||
const code = e.session ?? e.seance;
|
||
if (!date || !isText(code)) return null;
|
||
/** @type {import("./events.js").SessionData} */
|
||
const session = { date, kind: "strength", ref: code, name: isText(e.nom) ? e.nom : "Séance " + code, exercises: [], warmup: null };
|
||
if (code === "CARDIO") Object.assign(session, { kind: "cardio", name: isText(e.nom) ? e.nom : "Cardio", ref: isText(e.nom) ? e.nom : "Cardio" });
|
||
else if (code.startsWith("ACT:")) {
|
||
const id = activityIds.get(code.slice(4)) ?? code.slice(4);
|
||
Object.assign(session, { kind: "activity", ref: id, name: isText(e.nom) ? e.nom : id });
|
||
}
|
||
for (const x of Array.isArray(e.exercices) ? e.exercices : []) {
|
||
if (!isObject(x)) continue;
|
||
const done = Number.isInteger(x.series_validees) && x.series_validees > 0 ? x.series_validees : 0;
|
||
if (x.nom === "Échauffement" && !x.ref) {
|
||
const total = parseInt(String(x.objectif ?? ""), 10);
|
||
session.warmup = { done, total: Number.isInteger(total) && total >= done ? total : done };
|
||
continue;
|
||
}
|
||
const ref = isText(x.ref) ? ATELIER_REFS[/** @type {keyof typeof ATELIER_REFS} */ (x.ref)] : undefined;
|
||
const name = isText(x.nom) ? x.nom : isText(x.ref) ? x.ref : "Exercice";
|
||
const sets = (Array.isArray(x.series) ? x.series : []).filter(isObject).map((/** @type {any} */ s) => ({
|
||
reps: toNumber(s.reps), effort: EFFORT[s.effort] ?? null,
|
||
}));
|
||
while (sets.length < done) sets.push({ reps: null, effort: null });
|
||
const target = typeof x.objectif === "string" ? x.objectif : "";
|
||
const seconds = toNumber(x.duree_s);
|
||
const plannedSets = Number.isInteger(x.setsPrevues) && x.setsPrevues > 0 ? x.setsPrevues : null;
|
||
/** @type {ProgramExercise} */
|
||
const item = { sets: plannedSets ?? 1, reps: seconds !== null ? seconds + " s" : target.split("×").pop()?.trim() ?? "", rest: 0 };
|
||
if (ref) item.ref = ref;
|
||
session.exercises.push({
|
||
id: ref ?? name, name, target,
|
||
tracking: TRACKING[x.suivi] ?? trackingFor(item, undefined),
|
||
loadKg: toNumber(x.charge_kg), seconds, plannedSets, sets,
|
||
});
|
||
}
|
||
return session;
|
||
}
|
||
|
||
/**
|
||
* Profil tiré des consignes d'un export « pour LLM » (instructions.profil, materiel,
|
||
* contraintes). Le poids, propre au jour de l'export, vient des pesées.
|
||
* @param {unknown} instructions
|
||
* @returns {import("./profile.js").Profile|null}
|
||
*/
|
||
function profileFromInstructions(instructions) {
|
||
if (!isObject(instructions)) return null;
|
||
const ins = /** @type {Record<string, any>} */ (instructions);
|
||
const text = typeof ins.profil === "string" ? ins.profil : "";
|
||
const goalMatch = /Objectif\s*:\s*([^]*?)\s*$/i.exec(text);
|
||
const goal = goalMatch ? goalMatch[1].charAt(0).toUpperCase() + goalMatch[1].slice(1) : "";
|
||
// Contexte : les phrases entre le poids (première phrase) et l'objectif.
|
||
const before = goalMatch ? text.slice(0, goalMatch.index) : text;
|
||
const context = before.split(/(?<=\.)\s+/).slice(1).join(" ").trim();
|
||
const strings = (/** @type {unknown} */ x) => (Array.isArray(x) ? x.filter((s) => typeof s === "string") : []);
|
||
const constraints = strings(ins.contraintes);
|
||
const duration = constraints.map((c) => /(\d+)\s*à\s*(\d+)\s*min/.exec(c)).find(Boolean);
|
||
return {
|
||
...structuredClone(DEFAULT_PROFILE),
|
||
goal, context,
|
||
equipment: strings(ins.materiel),
|
||
constraints,
|
||
sessionMinutes: duration ? Math.round((Number(duration[1]) + Number(duration[2])) / 2) : DEFAULT_PROFILE.sessionMinutes,
|
||
};
|
||
}
|