sokko-g/website/src/features/toolboxes/modules/calculatorUtils.js
Shinuwa 08e28ee70d Evaluate calculator and goal tree formulas without eval
The production CSP forbids unsafe-eval, so the Function() call behind both
tools threw, every result came back empty and the calculator save and update
buttons stayed disabled in production. Dev worked because Vite sends no CSP.
Both now reuse the eval-free parser of the table formula engine, and a test
fails if client code evaluates strings again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 18:50:40 +01:00

107 lines
4 KiB
JavaScript

// Rôle : regroupe les helpers purs du calculateur et de son arbre de résultats.
import { evaluateArithmetic } from "./tableFormulaEngine.js";
export const DISPLAY_NUMBER_FORMATTER = new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 6 });
export const BASE_TOKEN = "base";
export function calculateExpression(expression, baseValue = null) {
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;
return evaluateArithmetic(withBase).value;
}
export function parseCalculatorCurrent(value) {
const normalized = String(value ?? "").replaceAll(",", ".").trim();
if (!normalized) return 0;
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : null;
}
export function calculateRemainingValue(expression, currentValue = 0, baseValue = null) {
const total = calculateExpression(expression, baseValue);
const current = parseCalculatorCurrent(currentValue);
if (total == null || current == null) return null;
return total - current;
}
export function formatResult(value) {
if (!Number.isFinite(value)) return "";
return Number.parseFloat(value.toFixed(6)).toString();
}
export function formatDisplayResult(value) {
if (!Number.isFinite(value)) return "";
return DISPLAY_NUMBER_FORMATTER.format(Number.parseFloat(value.toFixed(6)));
}
export function getResultLengthClass(value) {
const length = formatResult(value).replace(/[^\d]/g, "").length;
if (length >= 13) return "is-compact";
if (length >= 9) return "is-long";
return "";
}
export function getEntryResultLengthClass(value) {
const length = formatResult(value).replace(/[^\d]/g, "").length;
if (length >= 21) return "is-compact";
if (length >= 18) return "is-long";
return "";
}
export function getChildren(entries, parentId) {
return entries.filter((entry) => (entry.parentId || "") === parentId);
}
export function getDescendantIds(entries, parentId) {
const children = getChildren(entries, parentId);
return children.flatMap((child) => [child.id, ...getDescendantIds(entries, child.id)]);
}
export function getEntriesInTreeOrder(entries, parentId = "") {
return getChildren(entries, parentId).flatMap((entry) => [entry, ...getEntriesInTreeOrder(entries, entry.id)]);
}
export function getEntryFormula(entry) {
return String(entry?.formula || "").trim();
}
export function getEditableFormula(entry) {
const current = Number(entry?.current);
return getEntryFormula(entry) || formatResult(entry.value + (Number.isFinite(current) ? current : 0));
}
export function createStoredFormula(expression, parentValue) {
const normalized = String(expression || "").replaceAll(",", ".").trim();
if (!Number.isFinite(parentValue)) return normalized;
const parentText = formatResult(parentValue);
if (/\bbase\b/i.test(normalized)) return normalized;
const withBase = normalized.replace(new RegExp(`(^|[^\\d.])${escapeRegExp(parentText)}(?=$|[^\\d.])`, "g"), `$1${BASE_TOKEN}`);
if (withBase !== normalized) return withBase;
if (/^[+\-*/]/.test(normalized)) return `${BASE_TOKEN}${normalized}`;
return normalized;
}
export function evaluateCalculatorEntries(entries) {
const byParent = new Map();
entries.forEach((entry) => {
const parentId = entry.parentId || "";
byParent.set(parentId, [...(byParent.get(parentId) || []), entry]);
});
function visit(parentId = "", parentValue = null) {
return (byParent.get(parentId) || []).flatMap((entry) => {
const formula = getEntryFormula(entry);
const calculatedValue = formula ? calculateRemainingValue(formula, entry.current, parentValue) : entry.value;
const nextEntry = { ...entry, value: calculatedValue ?? entry.value };
return [nextEntry, ...visit(entry.id, nextEntry.value)];
});
}
return visit();
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}