// RĂ´le : regroupe les calculs purs de l'arbre d'objectifs. import { getLatestDailyReset, getLatestWeeklyReset } from "./resetUtils.js"; import { evaluateArithmetic } from "./tableFormulaEngine.js"; export const GOAL_TREE_KINDS = ["step", "text", "checklist"]; export const GOAL_TREE_RESET_TYPES = ["none", "daily", "weekly"]; export const GOAL_TREE_ICON_NAMES = ["cube", "fire", "flask", "grass", "leaf", "meat", "powder", "tear", "ball"]; export const GOAL_TREE_COLORS = ["gold", "cyan", "violet", "pink", "green", "gray", "red", "orange", "yellow", "blue", "indigo"]; export const GOAL_TREE_COLOR_VALUES = { gold: "#f6c453", cyan: "#22d3ee", violet: "#8b5cf6", pink: "#d946ef", green: "#34d399", gray: "#94a3b8", red: "#ef4444", orange: "#f97316", yellow: "#eab308", blue: "#3b82f6", indigo: "#6366f1" }; export const GOAL_TREE_WEEK_DAYS = [ { value: 1, label: "Lundi" }, { value: 2, label: "Mardi" }, { value: 3, label: "Mercredi" }, { value: 4, label: "Jeudi" }, { value: 5, label: "Vendredi" }, { value: 6, label: "Samedi" }, { value: 0, label: "Dimanche" } ]; function formatResult(value) { if (!Number.isFinite(value)) return ""; return Number.parseFloat(value.toFixed(6)).toString(); } export function calculateGoalTreeFormula(expression, baseValue = null, { clamp = true } = {}) { const normalized = String(expression || "").replaceAll(",", ".").trim(); if (!normalized) return null; const withBase = normalized.replace(/\bbase\b/gi, () => Number.isFinite(baseValue) ? `(${formatResult(baseValue)})` : "NaN"); if (!/^[\d\s+\-*/().]+$/.test(withBase)) return null; const { value } = evaluateArithmetic(withBase); if (value == null) return null; return clamp ? Math.max(0, value) : value; } export function formatGoalTreeNumber(value) { if (!Number.isFinite(value)) return "0"; return new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 2 }).format(Number.parseFloat(value.toFixed(2))); } export function getGoalTreeChildren(nodes, parentId) { return nodes.filter((node) => (node.parentId || "") === parentId); } export function getGoalTreeParentIds(node) { return [...new Set([node?.parentId || "", ...(Array.isArray(node?.parentIds) ? node.parentIds : [])].filter(Boolean))]; } export function getGoalTreeDescendantIds(nodes, parentId) { return getGoalTreeChildren(nodes, parentId).flatMap((child) => [child.id, ...getGoalTreeDescendantIds(nodes, child.id)]); } export function getGoalTreeParentMap(nodes) { const ids = new Set(nodes.map((node) => node.id)); return new Map(nodes.map((node) => [node.id, ids.has(node.parentId) ? node.parentId : ""])); } function isBaseScaledFormula(expression) { const normalized = String(expression || "").replaceAll(",", ".").trim(); return /\bbase\b/i.test(normalized) && /^[\d\s*/().base]+$/i.test(normalized); } export function evaluateGoalTreeNodes(nodes) { const nodeMap = new Map(nodes.map((node) => [node.id, node])); const childrenByParent = new Map(); nodes.forEach((node) => { const parentId = node.parentId || ""; childrenByParent.set(parentId, [...(childrenByParent.get(parentId) || []), node.id]); }); const computedTargets = new Map(); const progressMap = new Map(); function computeTarget(nodeId, seen = new Set()) { if (computedTargets.has(nodeId)) return computedTargets.get(nodeId); if (seen.has(nodeId)) return 1; const node = nodeMap.get(nodeId); if (!node) return 1; const parentTarget = node.parentId ? computeTarget(node.parentId, new Set([...seen, nodeId])) : null; const formulaTarget = node.formula ? calculateGoalTreeFormula(node.formula, parentTarget) : null; const target = Math.max(0, formulaTarget ?? node.qtyTarget ?? 1); computedTargets.set(nodeId, target); return target; } nodes.forEach((node) => computeTarget(node.id)); function evaluateChecklistItems(node) { const parentTarget = node.parentId ? computedTargets.get(node.parentId) : null; return (node.items || []).map((item) => { const target = calculateGoalTreeFormula(item.formula || "1", parentTarget) ?? item.qtyTarget ?? 1; return { ...item, qtyTarget: Math.max(1, target) }; }); } function getNodeProgressTarget(node) { if (node?.kind === "checklist") { return evaluateChecklistItems(node).reduce((sum, item) => sum + Math.max(1, item.qtyTarget || 1), 0) || 1; } if (node?.kind === "text") return Math.max(1, node.items?.length || 1); return Math.max(1, computedTargets.get(node?.id) ?? node?.qtyTarget ?? 1); } function getEffectiveStepProgressMode(node, childIds) { if (node?.kind !== "step") return "auto"; if (node?.progressMode) return node.progressMode; if (!childIds.length) return "manual"; return childIds.every((childId) => getNodeProgressTarget(nodeMap.get(childId)) <= 1) ? "manual" : "auto"; } function getBaseScaledRequirementCount(childNode, childProgress, parentTarget) { if (!parentTarget) return null; if (childNode.kind === "checklist") { const items = evaluateChecklistItems(childNode); if (!items.length || !items.every((item) => isBaseScaledFormula(item.formula))) return null; return items.map((item) => { const target = Math.max(1, item.qtyTarget || 1); const ratio = target / parentTarget; if (!ratio) return null; return Math.max(0, item.qtyCurrent || 0) / ratio; }); } if (!isBaseScaledFormula(childNode.formula)) return null; const target = Math.max(0, computedTargets.get(childNode.id) ?? childProgress.target ?? 0); const ratio = target / parentTarget; if (!ratio) return null; return [Math.max(0, childProgress.current || 0) / ratio]; } function computeBaseScaledChildrenProgress(node, childIds, childProgress) { const target = Math.max(1, computedTargets.get(node.id) ?? node.qtyTarget ?? 1); const requirementCounts = []; for (let index = 0; index < childIds.length; index += 1) { const childNode = nodeMap.get(childIds[index]); const counts = childNode ? getBaseScaledRequirementCount(childNode, childProgress[index], target) : null; if (!counts) return null; requirementCounts.push(...counts); } if (!requirementCounts.length) return null; const current = Math.min(target, Math.floor(Math.min(...requirementCounts))); return { current, target, ratio: target ? Math.min(1, current / target) : 0, complete: current >= target }; } function computeProgress(nodeId, seen = new Set()) { if (progressMap.has(nodeId)) return progressMap.get(nodeId); if (seen.has(nodeId)) return { current: 0, target: 1, ratio: 0, complete: false }; const node = nodeMap.get(nodeId); const childIds = childrenByParent.get(nodeId) || []; let progress; if (childIds.length && getEffectiveStepProgressMode(node, childIds) !== "manual") { const childProgress = childIds.map((childId) => computeProgress(childId, new Set([...seen, nodeId]))); progress = computeBaseScaledChildrenProgress(node, childIds, childProgress); if (!progress) { const target = childProgress.reduce((sum, item) => sum + item.target, 0); const current = childProgress.reduce((sum, item) => sum + Math.min(item.current, item.target), 0); progress = { current, target: target || 1, ratio: target ? Math.min(1, current / target) : 0, complete: childProgress.length > 0 && childProgress.every((item) => item.complete) }; } } else { const target = computedTargets.get(nodeId) ?? 1; const current = Math.max(0, node?.qtyCurrent || 0); if (node?.kind === "checklist") { const items = evaluateChecklistItems(node); const total = items.reduce((sum, item) => sum + Math.max(0, item.qtyTarget || 1), 0); const currentTotal = items.reduce((sum, item) => sum + Math.min(Math.max(0, item.qtyCurrent || 0), Math.max(0, item.qtyTarget || 1)), 0); progress = { current: currentTotal, target: total || 1, ratio: total ? currentTotal / total : 0, complete: items.length > 0 && currentTotal >= total }; } else if (node?.kind === "text") { const count = (node.items || []).length; progress = { current: count, target: count || 1, ratio: count ? 1 : 0, complete: count > 0 }; } else { progress = { current, target, ratio: target ? Math.min(1, current / target) : 1, complete: current >= target }; } } progressMap.set(nodeId, progress); return progress; } nodes.forEach((node) => computeProgress(node.id)); return nodes.map((node) => ({ ...node, items: node.kind === "checklist" ? evaluateChecklistItems(node) : node.items, computedQtyTarget: computedTargets.get(node.id) ?? node.qtyTarget, progress: progressMap.get(node.id) || { current: 0, target: 1, ratio: 0, complete: false } })); } export function applyGoalTreeDueResets(data, now = Date.now()) { let latestResetAt = data.lastResetAt || 0; let changed = false; const nodes = data.nodes.map((node) => { if (!["daily", "weekly"].includes(node.resetType)) return node; const resetAt = node.resetType === "daily" ? getLatestDailyReset(now, node.resetTime) : getLatestWeeklyReset(now, node.resetTime, node.weeklyResetDay); latestResetAt = Math.max(latestResetAt, resetAt); if (resetAt <= (node.checkedAt || data.lastResetAt || 0)) return node; if (node.kind === "checklist" && node.items?.some((item) => item.qtyCurrent)) { changed = true; return { ...node, items: node.items.map((item) => ({ ...item, qtyCurrent: 0 })), checkedAt: 0 }; } if (!node.qtyCurrent) return node; changed = true; return { ...node, qtyCurrent: 0, checkedAt: 0 }; }); if (latestResetAt > (data.lastResetAt || 0)) changed = true; return changed ? { ...data, lastResetAt: latestResetAt, nodes } : data; }