Domaine : tendance et repères du poids, import de pesées, export .ics
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
08b149ff0a
commit
8ca88e27d7
@@ -0,0 +1,182 @@
|
||||
// Export de la semaine au format iCalendar (.ics, RFC 5545), repris d'exportICS
|
||||
// d'Atelier. Corrige son identifiant d'événement : la même clé servait au cardio et
|
||||
// aux activités, et deux événements du même jour se confondaient dans l'agenda.
|
||||
|
||||
import { addDays } from "./dates.js";
|
||||
import { exerciseKey, resolveExercise, targetSeconds, trackingFor } from "./program.js";
|
||||
import { estimatedMinutes } from "./progression.js";
|
||||
import { slotRef, weekStatus } from "./planning.js";
|
||||
|
||||
/** @typedef {import("./state.js").State} State */
|
||||
/** @typedef {import("./planning.js").Slot} Slot */
|
||||
/** @typedef {import("./planning.js").WeekPlan} WeekPlan */
|
||||
|
||||
/** Libellés des zones, pour la description d'une activité. */
|
||||
const ZONE_LABELS = { cardio: "Cardio", lower: "Bas du corps", upper: "Haut du corps", core: "Tronc" };
|
||||
|
||||
/** Durées par défaut, en minutes. */
|
||||
const CARDIO_MINUTES = 50;
|
||||
const ACTIVITY_MINUTES = 90;
|
||||
|
||||
/** Échappe un texte (RFC 5545, 3.3.11). @param {string} text */
|
||||
export function icsEscape(text) {
|
||||
return String(text ?? "")
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/;/g, "\\;")
|
||||
.replace(/,/g, "\\,")
|
||||
.replace(/\r?\n/g, "\\n");
|
||||
}
|
||||
|
||||
/** @param {string} char */
|
||||
const byteLength = (char) => {
|
||||
const c = /** @type {number} */ (char.codePointAt(0));
|
||||
return c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
|
||||
};
|
||||
|
||||
/**
|
||||
* Plie une ligne de contenu : 75 octets au plus par ligne, et non 75 caractères
|
||||
* (un « é » en UTF-8 en fait deux). Les lignes de suite commencent par une espace,
|
||||
* comptée dans les 75 octets. Un caractère n'est jamais coupé.
|
||||
* @param {string} line
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function foldLine(line) {
|
||||
const out = [];
|
||||
let current = "";
|
||||
let size = 0;
|
||||
for (const char of line) {
|
||||
const n = byteLength(char);
|
||||
if (size + n > 75) {
|
||||
out.push(current);
|
||||
current = " ";
|
||||
size = 1;
|
||||
}
|
||||
current += char;
|
||||
size += n;
|
||||
}
|
||||
out.push(current);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** @param {number} n */
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
/** Horodatage UTC : 20261118T170500Z. @param {Date} d */
|
||||
function utcStamp(d) {
|
||||
return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Heure locale « flottante » (sans fuseau) : l'agenda la place à l'heure locale.
|
||||
* @param {string} date AAAA-MM-JJ
|
||||
* @param {number} minutes depuis minuit, éventuellement au-delà de 24 h
|
||||
*/
|
||||
function localStamp(date, minutes) {
|
||||
const day = addDays(date, Math.floor(minutes / 1440));
|
||||
const m = minutes % 1440;
|
||||
return `${day.replace(/-/g, "")}T${pad(Math.floor(m / 60))}${pad(m % 60)}00`;
|
||||
}
|
||||
|
||||
/** « 1 min 30 », « 45 s ». @param {number} s */
|
||||
function formatRest(s) {
|
||||
return s >= 60 ? `${Math.floor(s / 60)} min${s % 60 ? " " + (s % 60) : ""}` : `${s} s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifiant stable et unique d'un créneau : jour, nature et objet.
|
||||
* @param {Slot} slot
|
||||
*/
|
||||
export function slotUid(slot) {
|
||||
const what = slot.kind === "strength" ? slot.sessionKey : slot.kind === "cardio" ? slot.cardioIndex : slot.activityId;
|
||||
return `${slot.date}-${slot.kind}-${what}@ia-fit`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Titre, description et durée de l'événement d'un créneau.
|
||||
* @param {State} state
|
||||
* @param {Slot} slot
|
||||
* @returns {{title: string, description: string, minutes: number}|null}
|
||||
*/
|
||||
function describe(state, slot) {
|
||||
const program = /** @type {import("./program.js").Program|null} */ (state.program);
|
||||
if (!program) return null;
|
||||
if (slot.kind === "strength") {
|
||||
const session = program.sessions.find((s) => s.key === slot.sessionKey);
|
||||
if (!session) return null;
|
||||
const lines = session.exercises.map((item, j) => {
|
||||
const ex = resolveExercise(item);
|
||||
const key = exerciseKey(session.key, item);
|
||||
const mode = trackingFor(item, state.trackingOverrides[key]);
|
||||
const saved = state.workingLoads[key];
|
||||
let target;
|
||||
if (mode === "time" || mode === "time+load") {
|
||||
const seconds = saved?.seconds ?? targetSeconds(ex.reps) ?? 45;
|
||||
target = `${ex.sets} × ${seconds} s` + (mode === "time+load" && saved?.loadKg ? ` à ${saved.loadKg} kg` : "");
|
||||
} else {
|
||||
target = `${ex.sets} × ${ex.reps}` + (mode === "load" ? (saved?.loadKg ? ` à ${saved.loadKg} kg` : " — charge à définir") : "");
|
||||
}
|
||||
return `${j + 1}. ${ex.name} — ${target} (repos ${formatRest(ex.rest)})`;
|
||||
});
|
||||
return {
|
||||
title: `Séance ${session.key} — ${session.name}`,
|
||||
description: [session.subtitle ?? "", "", ...lines].join("\n").trim(),
|
||||
minutes: estimatedMinutes(session),
|
||||
};
|
||||
}
|
||||
if (slot.kind === "activity") {
|
||||
const activity = (program.activities ?? []).find((a) => a.id === slot.activityId);
|
||||
return {
|
||||
title: activity?.name ?? "Activité",
|
||||
description: activity ? "Sollicite : " + activity.zones.map((z) => ZONE_LABELS[z]).join(", ") + "." : "",
|
||||
minutes: activity?.minutes ?? ACTIVITY_MINUTES,
|
||||
};
|
||||
}
|
||||
const cardio = program.cardio?.[slot.cardioIndex ?? -1];
|
||||
return { title: "Cardio — " + slotRef(slot, program).ref, description: cardio?.text ?? "", minutes: CARDIO_MINUTES };
|
||||
}
|
||||
|
||||
/**
|
||||
* Créneaux d'une semaine à exporter : ni faits, ni marqués non faits.
|
||||
* @param {State} state
|
||||
* @param {WeekPlan} plan
|
||||
*/
|
||||
export function slotsToExport(state, plan) {
|
||||
const { bySlot } = weekStatus(state, plan);
|
||||
const skipped = new Set(state.skippedDays);
|
||||
return plan.slots.filter((s) => !bySlot.get(s)?.done && !skipped.has(s.date));
|
||||
}
|
||||
|
||||
/**
|
||||
* Le fichier .ics d'une semaine : un événement par créneau à faire, à l'heure
|
||||
* choisie, avec un rappel 30 minutes avant. Lignes séparées par CRLF et pliées à
|
||||
* 75 octets. Sans programme, un calendrier sans événement.
|
||||
* @param {State} state
|
||||
* @param {WeekPlan} plan
|
||||
* @param {{hour: number, minute: number, now: Date}} options `now` sert à l'horodatage DTSTAMP
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildIcs(state, plan, { hour, minute, now }) {
|
||||
const lines = [
|
||||
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//IA-Fit//Planning//FR",
|
||||
"CALSCALE:GREGORIAN", "METHOD:PUBLISH", ...foldLine("X-WR-CALNAME:" + icsEscape(/** @type {import("./program.js").Program|null} */ (state.program)?.name || "IA-Fit")),
|
||||
];
|
||||
const start = hour * 60 + minute;
|
||||
for (const slot of slotsToExport(state, plan)) {
|
||||
const event = describe(state, slot);
|
||||
if (!event) continue;
|
||||
lines.push(
|
||||
"BEGIN:VEVENT",
|
||||
"UID:" + slotUid(slot),
|
||||
"DTSTAMP:" + utcStamp(now),
|
||||
"DTSTART:" + localStamp(slot.date, start),
|
||||
"DTEND:" + localStamp(slot.date, start + event.minutes),
|
||||
...foldLine("SUMMARY:" + icsEscape(event.title)),
|
||||
...foldLine("DESCRIPTION:" + icsEscape(event.description)),
|
||||
"BEGIN:VALARM", "TRIGGER:-PT30M", "ACTION:DISPLAY",
|
||||
...foldLine("DESCRIPTION:" + icsEscape(event.title)),
|
||||
"END:VALARM", "END:VEVENT",
|
||||
);
|
||||
}
|
||||
lines.push("END:VCALENDAR");
|
||||
return lines.join("\r\n") + "\r\n";
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Poids corporel : tendance, repères et import en texte libre. Repris
|
||||
// d'analysePoids, jalonsPoids et importerPesees d'Atelier.
|
||||
|
||||
import { addDays, daysBetween } from "./dates.js";
|
||||
|
||||
/** @typedef {{date: string, kg: number}} Weighing */
|
||||
|
||||
/** @param {readonly Weighing[]} weights */
|
||||
const sorted = (weights) => [...weights].sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
|
||||
|
||||
/**
|
||||
* @typedef {object} WeightTrend
|
||||
* @property {number} kgPerWeek pente de la droite de régression, en kg par semaine
|
||||
* @property {string} from première pesée de la fenêtre
|
||||
* @property {string} to dernière pesée
|
||||
* @property {number} count pesées dans la fenêtre
|
||||
* @property {number|null} staleDays jours écoulés entre la dernière pesée et `today` (null sans `today`)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Tendance du poids par régression linéaire sur une fenêtre de `windowDays`
|
||||
* jours. La fenêtre part de la dernière pesée, pas d'aujourd'hui : après une
|
||||
* pause de pesées, la tendance reste celle des dernières semaines mesurées
|
||||
* (`staleDays` dit depuis quand). Il faut au moins deux pesées à des jours
|
||||
* différents dans la fenêtre.
|
||||
* @param {readonly Weighing[]} weights
|
||||
* @param {{windowDays?: number, today?: string}} [options]
|
||||
* @returns {WeightTrend|null}
|
||||
*/
|
||||
export function weightTrend(weights, { windowDays = 56, today } = {}) {
|
||||
const all = sorted(weights);
|
||||
if (all.length < 2) return null;
|
||||
const last = all[all.length - 1];
|
||||
const points = all.filter((w) => w.date >= addDays(last.date, -windowDays));
|
||||
const first = points[0];
|
||||
if (points.length < 2 || first.date === last.date) return null;
|
||||
const xs = points.map((w) => daysBetween(first.date, w.date));
|
||||
const ys = points.map((w) => w.kg);
|
||||
const mx = xs.reduce((a, b) => a + b, 0) / xs.length;
|
||||
const my = ys.reduce((a, b) => a + b, 0) / ys.length;
|
||||
let num = 0, den = 0;
|
||||
for (let i = 0; i < xs.length; i++) {
|
||||
num += (xs[i] - mx) * (ys[i] - my);
|
||||
den += (xs[i] - mx) ** 2;
|
||||
}
|
||||
return {
|
||||
kgPerWeek: den ? (num / den) * 7 : 0,
|
||||
from: first.date,
|
||||
to: last.date,
|
||||
count: points.length,
|
||||
staleDays: today ? Math.max(0, daysBetween(last.date, today)) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} WeightMilestones
|
||||
* @property {Weighing} current dernière pesée
|
||||
* @property {Weighing|null} lastBelow la dernière fois sous le poids actuel
|
||||
* @property {number|null} daysSinceLastBelow
|
||||
* @property {Weighing[]} below pesées antérieures sous le poids actuel, de la plus récente à la plus ancienne
|
||||
* @property {Weighing} minimum la plus basse (la plus ancienne à égalité)
|
||||
* @property {number} daysSinceMinimum
|
||||
*/
|
||||
|
||||
/**
|
||||
* Repères : depuis quand n'as-tu pas été aussi léger, et ton minimum. Les durées
|
||||
* se comptent depuis la dernière pesée. Il faut au moins deux pesées.
|
||||
* @param {readonly Weighing[]} weights
|
||||
* @returns {WeightMilestones|null}
|
||||
*/
|
||||
export function weightMilestones(weights) {
|
||||
const all = sorted(weights);
|
||||
if (all.length < 2) return null;
|
||||
const current = all[all.length - 1];
|
||||
const below = all.slice(0, -1).filter((w) => w.kg < current.kg).reverse();
|
||||
const minimum = all.reduce((a, b) => (b.kg < a.kg ? b : a));
|
||||
const lastBelow = below[0] ?? null;
|
||||
return {
|
||||
current,
|
||||
lastBelow,
|
||||
daysSinceLastBelow: lastBelow ? daysBetween(lastBelow.date, current.date) : null,
|
||||
below,
|
||||
minimum,
|
||||
daysSinceMinimum: daysBetween(minimum.date, current.date),
|
||||
};
|
||||
}
|
||||
|
||||
const LINE = /^(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})\s*[,;\t ]\s*(\d+(?:[.,]\d+)?)/;
|
||||
|
||||
/**
|
||||
* Import souple : une pesée par ligne, une date (AAAA-MM-JJ ou JJ/MM/AAAA, avec
|
||||
* « / » ou « . », année sur deux chiffres admise) puis un poids (virgule ou
|
||||
* point décimal), séparés par une espace, une tabulation, « ; » ou « , ».
|
||||
* Les lignes vides sont ignorées ; les autres lignes illisibles, aux dates
|
||||
* impossibles ou au poids hors de 20 à 400 kg sont rendues dans `rejected`.
|
||||
* @param {string} text
|
||||
* @returns {{entries: Weighing[], rejected: string[]}}
|
||||
*/
|
||||
export function parseWeightLines(text) {
|
||||
/** @type {Weighing[]} */
|
||||
const entries = [];
|
||||
/** @type {string[]} */
|
||||
const rejected = [];
|
||||
for (const line of String(text ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) {
|
||||
const m = LINE.exec(line);
|
||||
const date = m ? normalizeDate(m[1]) : null;
|
||||
const kg = m ? Number(m[2].replace(",", ".")) : NaN;
|
||||
if (!date || !(kg >= 20 && kg <= 400)) rejected.push(line);
|
||||
else entries.push({ date, kg });
|
||||
}
|
||||
return { entries, rejected };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} raw AAAA-MM-JJ ou JJ/MM/AAAA
|
||||
* @returns {string|null} AAAA-MM-JJ, ou null si la date n'existe pas
|
||||
*/
|
||||
function normalizeDate(raw) {
|
||||
let iso = raw;
|
||||
if (!raw.includes("-")) {
|
||||
const [d, m, y] = raw.split(/[/.]/);
|
||||
if (y.length === 3) return null;
|
||||
iso = `${y.length === 2 ? "20" + y : y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
|
||||
}
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
const check = new Date(Date.UTC(y, m - 1, d));
|
||||
return check.getUTCFullYear() === y && check.getUTCMonth() === m - 1 && check.getUTCDate() === d ? iso : null;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { emptyState } from "../../app/domain/state.js";
|
||||
import { DEFAULT_PROGRAM } from "../../app/domain/default-program.js";
|
||||
import { weekPlan } from "../../app/domain/planning.js";
|
||||
import { buildIcs, foldLine, icsEscape } from "../../app/domain/ics.js";
|
||||
|
||||
const MONDAY = "2026-11-16";
|
||||
const NOW = new Date("2026-11-18T17:05:00Z");
|
||||
|
||||
/** Une semaine complète : force, cardio et une activité au nom accentué. */
|
||||
function fullWeek() {
|
||||
const s = emptyState();
|
||||
s.program = structuredClone(DEFAULT_PROGRAM);
|
||||
s.program.activities = [{
|
||||
id: "randonnee", name: "Randonnée en forêt, dénivelé élevé ; « été »", zones: ["cardio", "lower"], intensity: "moderate", minutes: 180,
|
||||
}];
|
||||
s.planSettings = { days: [0, 1, 2, 3, 4, 5], locks: { 6: "activity:randonnee" } };
|
||||
return s;
|
||||
}
|
||||
|
||||
/** @param {string} text */
|
||||
const physicalLines = (text) => text.split("\r\n").slice(0, -1);
|
||||
/** @param {string} text */
|
||||
const unfold = (text) => text.replace(/\r\n /g, "").split("\r\n").slice(0, -1);
|
||||
/** @param {string} text */
|
||||
const events = (text) => text.split("BEGIN:VEVENT").slice(1);
|
||||
|
||||
test("pliage .ics avec accents : 75 octets au plus, jamais au milieu d'un caractère", () => {
|
||||
const line = "SUMMARY:" + "é".repeat(100) + "€🏋";
|
||||
const folded = foldLine(line);
|
||||
assert.ok(folded.length > 1);
|
||||
for (const l of folded) assert.ok(Buffer.byteLength(l, "utf8") <= 75, `${Buffer.byteLength(l, "utf8")} octets`);
|
||||
assert.ok(folded.slice(1).every((l) => l.startsWith(" ")));
|
||||
assert.equal(folded.map((l, i) => (i ? l.slice(1) : l)).join(""), line);
|
||||
// en caractères, la première ligne fait bien moins de 75 : c'est l'octet qui compte
|
||||
assert.ok(folded[0].length < 75);
|
||||
assert.deepEqual(foldLine("UID:court"), ["UID:court"]);
|
||||
});
|
||||
|
||||
test("le fichier entier respecte le pliage et se déplie à l'identique", () => {
|
||||
const s = fullWeek();
|
||||
const text = buildIcs(s, weekPlan(s, MONDAY), { hour: 18, minute: 0, now: NOW });
|
||||
assert.ok(text.startsWith("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"));
|
||||
assert.ok(text.endsWith("END:VCALENDAR\r\n"));
|
||||
for (const l of physicalLines(text)) assert.ok(Buffer.byteLength(l, "utf8") <= 75, l);
|
||||
const summaries = unfold(text).filter((l) => l.startsWith("SUMMARY:"));
|
||||
assert.ok(summaries.includes("SUMMARY:Randonnée en forêt\\, dénivelé élevé \\; « été »"));
|
||||
});
|
||||
|
||||
test("UID distincts : un par créneau, la nature du créneau en fait partie", () => {
|
||||
const s = fullWeek();
|
||||
const plan = weekPlan(s, MONDAY);
|
||||
const text = buildIcs(s, plan, { hour: 18, minute: 0, now: NOW });
|
||||
const uids = unfold(text).filter((l) => l.startsWith("UID:"));
|
||||
assert.equal(uids.length, plan.slots.length);
|
||||
assert.equal(new Set(uids).size, uids.length);
|
||||
assert.ok(uids.some((u) => u.includes("-cardio-")));
|
||||
assert.ok(uids.includes("UID:2026-11-22-activity-randonnee@ia-fit"));
|
||||
});
|
||||
|
||||
test("chaque événement a son horaire, sa durée et un rappel 30 min avant", () => {
|
||||
const s = fullWeek();
|
||||
const text = buildIcs(s, weekPlan(s, MONDAY), { hour: 18, minute: 30, now: NOW });
|
||||
const first = events(text)[0];
|
||||
assert.match(first, /DTSTAMP:20261118T170500Z/);
|
||||
assert.match(first, /DTSTART:20261116T183000\r\n/);
|
||||
assert.match(first, /DTEND:20261116T191500\r\n/, "séance A : 45 minutes");
|
||||
assert.match(first, /SUMMARY:Séance A — Bas du corps \+ dos/);
|
||||
assert.match(first, /BEGIN:VALARM\r\nTRIGGER:-PT30M\r\nACTION:DISPLAY/);
|
||||
assert.match(unfold(text).join("\n"), /1\. Squat barre — 4 × 8 — charge à définir \(repos 2 min\)/);
|
||||
// une fin après minuit passe au lendemain
|
||||
const late = buildIcs(s, weekPlan(s, MONDAY), { hour: 23, minute: 0, now: NOW });
|
||||
assert.match(events(late).at(-1) ?? "", /DTSTART:20261122T230000\r\nDTEND:20261123T020000/);
|
||||
});
|
||||
|
||||
test("créneaux faits ou marqués non faits exclus de l'export", () => {
|
||||
const s = fullWeek();
|
||||
const plan = weekPlan(s, MONDAY);
|
||||
s.skippedDays = [plan.slots[1].date];
|
||||
s.sessions = [{
|
||||
id: "x", loggedAt: "2026-11-16T19:00:00Z", date: "2026-11-16", kind: "strength", ref: plan.slots[0].sessionKey ?? "", name: "A", warmup: null, exercises: [],
|
||||
}];
|
||||
const text = buildIcs(s, plan, { hour: 18, minute: 0, now: NOW });
|
||||
assert.equal(events(text).length, plan.slots.length - 2);
|
||||
assert.ok(!text.includes("DTSTART:20261116"));
|
||||
assert.ok(!text.includes("DTSTART:20261117"));
|
||||
});
|
||||
|
||||
test("sans programme, un calendrier sans événement", () => {
|
||||
const s = fullWeek();
|
||||
const plan = weekPlan(s, MONDAY);
|
||||
s.program = /** @type {any} */ (null);
|
||||
const text = buildIcs(s, plan, { hour: 18, minute: 0, now: NOW });
|
||||
assert.equal(events(text).length, 0);
|
||||
assert.match(text, /X-WR-CALNAME:IA-Fit/);
|
||||
});
|
||||
|
||||
test("échappement des caractères spéciaux", () => {
|
||||
assert.equal(icsEscape("a,b;c\\d\ne"), "a\\,b\\;c\\\\d\\ne");
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { addDays } from "../../app/domain/dates.js";
|
||||
import { parseWeightLines, weightMilestones, weightTrend } from "../../app/domain/weight.js";
|
||||
|
||||
/** Pesées hebdomadaires à partir de `start`, en perdant `perWeek` kg par semaine. */
|
||||
function weekly(start = "2026-01-05", count = 9, from = 110, perWeek = 1) {
|
||||
return Array.from({ length: count }, (_, i) => ({ date: addDays(start, 7 * i), kg: from - perWeek * i }));
|
||||
}
|
||||
|
||||
test("tendance : pente de la régression, en kg par semaine", () => {
|
||||
const trend = weightTrend(weekly());
|
||||
assert.ok(trend);
|
||||
assert.ok(Math.abs(trend.kgPerWeek + 1) < 1e-9);
|
||||
assert.equal(trend.to, "2026-03-02");
|
||||
assert.equal(trend.from, "2026-01-05");
|
||||
assert.equal(trend.count, 9);
|
||||
assert.equal(trend.staleDays, null);
|
||||
});
|
||||
|
||||
test("tendance après une pause de pesées : la fenêtre part de la dernière pesée", () => {
|
||||
// dernière pesée le 2 mars, trois mois sans peser : la tendance reste lisible
|
||||
const trend = weightTrend(weekly(), { today: "2026-06-01" });
|
||||
assert.ok(trend);
|
||||
assert.ok(Math.abs(trend.kgPerWeek + 1) < 1e-9);
|
||||
assert.equal(trend.staleDays, 91);
|
||||
});
|
||||
|
||||
test("tendance : seules les pesées de la fenêtre comptent", () => {
|
||||
// une prise rapide il y a longtemps, puis une baisse régulière
|
||||
const weights = [{ date: "2025-06-01", kg: 90 }, ...weekly("2026-01-05", 9, 110, 0.5)];
|
||||
const trend = weightTrend(weights, { windowDays: 56 });
|
||||
assert.equal(trend?.from, "2026-01-05");
|
||||
assert.ok(Math.abs((trend?.kgPerWeek ?? 0) + 0.5) < 1e-9);
|
||||
assert.equal(weightTrend(weights, { windowDays: 14 })?.count, 3);
|
||||
});
|
||||
|
||||
test("tendance : il faut deux pesées dans la fenêtre", () => {
|
||||
assert.equal(weightTrend([]), null);
|
||||
assert.equal(weightTrend([{ date: "2026-01-01", kg: 100 }]), null);
|
||||
assert.equal(weightTrend([{ date: "2025-01-01", kg: 100 }, { date: "2026-01-01", kg: 99 }]), null);
|
||||
});
|
||||
|
||||
test("repères : la dernière fois sous le poids actuel, et le minimum", () => {
|
||||
const weights = [
|
||||
{ date: "2026-01-01", kg: 100 }, { date: "2026-02-01", kg: 95 }, { date: "2026-03-01", kg: 97 },
|
||||
{ date: "2026-04-01", kg: 99 }, { date: "2026-05-01", kg: 98 },
|
||||
];
|
||||
const m = weightMilestones(weights);
|
||||
assert.deepEqual(m?.current, { date: "2026-05-01", kg: 98 });
|
||||
assert.deepEqual(m?.lastBelow, { date: "2026-03-01", kg: 97 });
|
||||
assert.equal(m?.daysSinceLastBelow, 61);
|
||||
assert.deepEqual(m?.below.map((w) => w.date), ["2026-03-01", "2026-02-01"]);
|
||||
assert.deepEqual(m?.minimum, { date: "2026-02-01", kg: 95 });
|
||||
assert.equal(m?.daysSinceMinimum, 89);
|
||||
});
|
||||
|
||||
test("repères : au plus bas, aucune pesée antérieure n'est plus légère", () => {
|
||||
const m = weightMilestones([{ date: "2026-01-01", kg: 100 }, { date: "2026-02-01", kg: 96 }]);
|
||||
assert.equal(m?.lastBelow, null);
|
||||
assert.equal(m?.daysSinceLastBelow, null);
|
||||
assert.deepEqual(m?.minimum, { date: "2026-02-01", kg: 96 });
|
||||
assert.equal(weightMilestones([{ date: "2026-01-01", kg: 100 }]), null);
|
||||
});
|
||||
|
||||
test("import en texte libre : dates ISO ou françaises, virgule ou point", () => {
|
||||
const text = [
|
||||
"2026-11-18 109,4",
|
||||
"17/11/2026;109.8",
|
||||
" 3.11.26\t110 ",
|
||||
"",
|
||||
"2026-11-01, 111,2",
|
||||
"hier 110",
|
||||
"31/02/2026 110",
|
||||
"2026-11-02 12",
|
||||
].join("\r\n");
|
||||
const { entries, rejected } = parseWeightLines(text);
|
||||
assert.deepEqual(entries, [
|
||||
{ date: "2026-11-18", kg: 109.4 },
|
||||
{ date: "2026-11-17", kg: 109.8 },
|
||||
{ date: "2026-11-03", kg: 110 },
|
||||
{ date: "2026-11-01", kg: 111.2 },
|
||||
]);
|
||||
assert.deepEqual(rejected, ["hier 110", "31/02/2026 110", "2026-11-02 12"]);
|
||||
});
|
||||
Reference in New Issue
Block a user