formlab-mcp 0.6.72 → 0.6.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.json +2 -2
- package/theoretical.js +5 -3
- package/tools/formulations.js +1 -1
- package/vendor/theoretical-params.js +226 -23
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.73",
|
|
4
4
|
"mcpName": "io.github.juliu1980/formlab-mcp",
|
|
5
5
|
"description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
|
|
6
6
|
"homepage": "https://formvix.com/mcp",
|
package/server.json
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.juliu1980/formlab-mcp",
|
|
4
4
|
"description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
|
|
5
|
-
"version": "0.6.
|
|
5
|
+
"version": "0.6.73",
|
|
6
6
|
"websiteUrl": "https://formvix.com/mcp",
|
|
7
7
|
"packages": [
|
|
8
8
|
{
|
|
9
9
|
"registryType": "npm",
|
|
10
10
|
"identifier": "formlab-mcp",
|
|
11
|
-
"version": "0.6.
|
|
11
|
+
"version": "0.6.73",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/theoretical.js
CHANGED
|
@@ -56,13 +56,15 @@ function __theo(kind, id) {
|
|
|
56
56
|
var res = _tpEvaluateAll(params, rows);
|
|
57
57
|
return JSON.stringify(params.map(function (p) {
|
|
58
58
|
var r = res[p.id] || {};
|
|
59
|
-
|
|
59
|
+
// A number, or text from an IF (49v); spec / pass apply to numbers only.
|
|
60
|
+
var v = (!r.error && (Number.isFinite(r.value) || (typeof r.value === 'string' && r.value))) ? r.value : null;
|
|
60
61
|
var warning = null;
|
|
61
62
|
try { var m = r.needsDensity ? _tpNeedsDensityNote(r.needsDensity) : _tpMissingNote(_tpMissingInputs(p.formula, rows)); if (m) warning = m.text; } catch (_) {}
|
|
62
63
|
var spec = (p.spec && (p.spec.min != null || p.spec.max != null)) ? { min: p.spec.min != null ? p.spec.min : null, max: p.spec.max != null ? p.spec.max : null } : null;
|
|
63
|
-
var pass = (v
|
|
64
|
+
var pass = (typeof v === 'number' && spec) ? ((spec.min == null || v >= spec.min) && (spec.max == null || v <= spec.max)) : null;
|
|
64
65
|
return { name: p.name || '', value: v, unit: p.unit || '', formula: p.formula || '', error: r.error || null,
|
|
65
|
-
warning:
|
|
66
|
+
warning: r.held ? 'No result: a text result waits until every ingredient value it reads is there' + (warning ? ' (' + warning + ')' : '') : warning,
|
|
67
|
+
spec: spec, pass: pass, pinned: !!p.pinned, basis: comp.source };
|
|
66
68
|
}));
|
|
67
69
|
}`;
|
|
68
70
|
|
package/tools/formulations.js
CHANGED
|
@@ -115,7 +115,7 @@ const list_formulations = {
|
|
|
115
115
|
const get_formulation = {
|
|
116
116
|
definition: {
|
|
117
117
|
name: 'get_formulation',
|
|
118
|
-
description: 'Get full details for a single formulation including its composition (raw rows AND flattened wt-% leaves with sub-formulas expanded), step procedure, any recorded process-factor values (cure temp, mix time, RPM, pH — DOE inputs), and recent batches. Accepts either internal id or UID (e.g. FORM-001). Also returns `theoreticalParameters`: values computed from the composition the way the app Params tab does (e.g. Energy kcal/100g, NV %, Cost/kg) — each with name, value, unit, formula, spec + pass, and `warning` when ingredients lack a value the formula reads or carry mixed units (those rows are not counted). Quote these; do not recompute nutrition or NV yourself. `versionLabel` is the label the user types (e.g. 1.0); `versionHistory` is the automatic save history (v1, v2… one per save, newest first, up to 20, with the label each save had and its note) — two different things.',
|
|
118
|
+
description: 'Get full details for a single formulation including its composition (raw rows AND flattened wt-% leaves with sub-formulas expanded), step procedure, any recorded process-factor values (cure temp, mix time, RPM, pH — DOE inputs), and recent batches. Accepts either internal id or UID (e.g. FORM-001). Also returns `theoreticalParameters`: values computed from the composition the way the app Params tab does (e.g. Energy kcal/100g, NV %, Cost/kg) — each with name, value (a number, or text when the formula is an IF that gives text), unit, formula, spec + pass (numbers only), and `warning` when ingredients lack a value the formula reads or carry mixed units (those rows are not counted). Quote these; do not recompute nutrition or NV yourself. `versionLabel` is the label the user types (e.g. 1.0); `versionHistory` is the automatic save history (v1, v2… one per save, newest first, up to 20, with the label each save had and its note) — two different things.',
|
|
119
119
|
inputSchema: {
|
|
120
120
|
type: 'object',
|
|
121
121
|
properties: {
|
|
@@ -38,6 +38,13 @@
|
|
|
38
38
|
// Outside aggregations: arithmetic only (+ - * / parens, numbers,
|
|
39
39
|
// constants PI/E). Bare row./ing. outside an aggregation throws.
|
|
40
40
|
//
|
|
41
|
+
// Conditions (49v): IF(test, then, else) gives one of two values, a number
|
|
42
|
+
// or text in quotes, e.g. IF([VOC] < 50, 'Low VOC', 'Standard'). Nest for
|
|
43
|
+
// more cases: IF([pH] < 5, 'acidic', IF([pH] > 9, 'basic', 'neutral')).
|
|
44
|
+
// Tests use < <= > >= == != with && || !; inside an aggregation IF works per
|
|
45
|
+
// row: SUM(IF(ing.state == 'liquid', row.amount, 0)). A text result shows as
|
|
46
|
+
// it is (no spec), and [Text parameter] can be compared: [Flag] == 'Low VOC'.
|
|
47
|
+
//
|
|
41
48
|
// Cross-parameter references:
|
|
42
49
|
// [Param Name] — another parameter's computed value
|
|
43
50
|
// e.g. [Total cost] / [Total weight]
|
|
@@ -52,6 +59,10 @@ function _tpCompile(formula) {
|
|
|
52
59
|
let src = String(formula || '').trim();
|
|
53
60
|
if (!src) throw new Error('Empty formula');
|
|
54
61
|
|
|
62
|
+
// 0. An IF's test compares through _tpCmp, so a comparison on a missing
|
|
63
|
+
// number gives no value instead of the else side (49w).
|
|
64
|
+
src = _tpRewriteIfTests(src);
|
|
65
|
+
|
|
55
66
|
// 1. Rewrite aggregation calls into (condFn, exprFn) form.
|
|
56
67
|
// Iterate because inner aggregations may appear after outer rewrite.
|
|
57
68
|
src = _tpRewriteAggs(src);
|
|
@@ -60,7 +71,9 @@ function _tpCompile(formula) {
|
|
|
60
71
|
// function only has SUM/AVG/MIN/MAX/COUNT in scope (no globals,
|
|
61
72
|
// no this, no Function/eval/import), and arrow fns inside
|
|
62
73
|
// aggregations capture `r` as the iteration variable.
|
|
63
|
-
|
|
74
|
+
// Text inside quotes is data (49v: IF(…, 'Low VOC ≤ 50 g/L', …)); only the
|
|
75
|
+
// code around it is held to the list.
|
|
76
|
+
if (!/^[a-zA-Z0-9_\[\]\.\s+\-*/(),<>=!&|?:%'"]+$/.test(_tpStripStrings(src))) {
|
|
64
77
|
throw new Error('Formula contains disallowed characters. Allowed: letters, digits, _ [ ] . ( ) , + - * / < > = ! & | ? : % \' "');
|
|
65
78
|
}
|
|
66
79
|
|
|
@@ -80,7 +93,7 @@ function _tpCompile(formula) {
|
|
|
80
93
|
// as locals. Any syntax error surfaces with a meaningful message.
|
|
81
94
|
try {
|
|
82
95
|
// eslint-disable-next-line no-new-func
|
|
83
|
-
return new Function('SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas',
|
|
96
|
+
return new Function('SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas', 'IF', '_tpCmp',
|
|
84
97
|
`"use strict"; return (${src});`);
|
|
85
98
|
} catch (e) {
|
|
86
99
|
throw new Error(`Parse error: ${e.message}`);
|
|
@@ -88,25 +101,28 @@ function _tpCompile(formula) {
|
|
|
88
101
|
}
|
|
89
102
|
|
|
90
103
|
const _TP_SAFE_NAMES = new Set([
|
|
91
|
-
'SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas',
|
|
104
|
+
'SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas', 'IF', '_tpCmp',
|
|
92
105
|
'r', 'ing', 'amount', 'unit', 'role', 'null', 'true', 'false', 'undefined',
|
|
93
106
|
'NaN', 'Infinity', // an unknown [Param] is substituted as (NaN)
|
|
94
107
|
]);
|
|
108
|
+
function _tpStripStrings(src) {
|
|
109
|
+
return String(src).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
|
|
110
|
+
}
|
|
95
111
|
function _tpCheckNames(src) {
|
|
96
|
-
const noStr =
|
|
112
|
+
const noStr = _tpStripStrings(src);
|
|
97
113
|
// Numbers first (1e3, 2.5E-2) so their exponent isn't read as a name.
|
|
98
114
|
const noNum = noStr.replace(/\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\.\d+(?:[eE][+-]?\d+)?\b/g, '0');
|
|
99
115
|
for (const id of (noNum.match(/[A-Za-z_$][A-Za-z0-9_$]*/g) || [])) {
|
|
100
116
|
if (!_TP_SAFE_NAMES.has(id)) {
|
|
101
|
-
throw new Error(`"${id}" isn't part of the formula language. Use SUM / AVG / MIN / MAX / COUNT, row.amount, ing.<field> or ing['Field name'], numbers and [Other parameter].`);
|
|
117
|
+
throw new Error(`"${id}" isn't part of the formula language. Use SUM / AVG / MIN / MAX / COUNT, IF, row.amount, ing.<field> or ing['Field name'], numbers and [Other parameter].`);
|
|
102
118
|
}
|
|
103
119
|
}
|
|
104
120
|
// Nothing in the language calls the result of a lookup or a bracket: the
|
|
105
121
|
// only calls are SUM( … ) and the like, by name. `ing['x'](…)` or `(…)(…)`
|
|
106
122
|
// can only be an attempt to call something.
|
|
107
|
-
const called = (noNum.match(/[A-Za-z_$][A-Za-z0-9_$]*(?=\s*\()/g) || []).filter(n => !/^(SUM|AVG|MEAN|MIN|MAX|COUNT|_tpNum|_tpHas)$/.test(n));
|
|
123
|
+
const called = (noNum.match(/[A-Za-z_$][A-Za-z0-9_$]*(?=\s*\()/g) || []).filter(n => !/^(SUM|AVG|MEAN|MIN|MAX|COUNT|IF|_tpNum|_tpHas|_tpCmp)$/.test(n));
|
|
108
124
|
if (called.length || /[\])]\s*\(/.test(noStr)) {
|
|
109
|
-
throw new Error("A value can't be called like a function — only SUM / AVG / MIN / MAX / COUNT take parentheses.");
|
|
125
|
+
throw new Error("A value can't be called like a function — only SUM / AVG / MIN / MAX / COUNT and IF take parentheses.");
|
|
110
126
|
}
|
|
111
127
|
for (let i = noStr.indexOf('['); i >= 0; i = noStr.indexOf('[', i + 1)) {
|
|
112
128
|
if (!/\br\s*\.\s*ing\s*$/.test(noStr.slice(0, i))) {
|
|
@@ -274,8 +290,102 @@ function _tpEvaluate(formula, rows) {
|
|
|
274
290
|
const vals = Array.isArray(field) ? field : String(field == null ? '' : field).split('|');
|
|
275
291
|
return vals.some(v => String(v).trim().toLowerCase() === want);
|
|
276
292
|
};
|
|
277
|
-
return fn(SUM, AVG, AVG, MIN, MAX, COUNT, Math.PI, Math.E, _tpNum, _tpHas);
|
|
293
|
+
return _tpResult(fn(SUM, AVG, AVG, MIN, MAX, COUNT, Math.PI, Math.E, _tpNum, _tpHas, _tpIF, _tpCmp));
|
|
294
|
+
}
|
|
295
|
+
// IF(test, then, else): else left out = no value. Both sides are worked out
|
|
296
|
+
// (nothing in the language has side effects). A test that compared a missing
|
|
297
|
+
// number is NaN (_tpCmp), and gives no value: an empty recipe is not "Standard".
|
|
298
|
+
function _tpIF(test, a, b) {
|
|
299
|
+
if (typeof test === 'number' && Number.isNaN(test)) return null;
|
|
300
|
+
return test ? a : (b === undefined ? null : b);
|
|
301
|
+
}
|
|
302
|
+
// < <= > >= inside an IF's test: two texts compare as text; otherwise both
|
|
303
|
+
// sides must be numbers, or the answer is NaN (unknown), which && and ||
|
|
304
|
+
// carry through (NaN && x is NaN; false || NaN is NaN).
|
|
305
|
+
function _tpCmp(a, op, b) {
|
|
306
|
+
if (typeof a === 'string' && typeof b === 'string') return op === '<' ? a < b : op === '<=' ? a <= b : op === '>' ? a > b : a >= b;
|
|
307
|
+
const x = (typeof a === 'number') ? a : (a == null || a === '' ? NaN : Number(a));
|
|
308
|
+
const y = (typeof b === 'number') ? b : (b == null || b === '' ? NaN : Number(b));
|
|
309
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return NaN;
|
|
310
|
+
return op === '<' ? x < y : op === '<=' ? x <= y : op === '>' ? x > y : x >= y;
|
|
311
|
+
}
|
|
312
|
+
// Source scanning that steps over quoted text: calls fn(i, ch, depth) for each
|
|
313
|
+
// character outside quotes; fn returns true to stop. Returns the stop index or -1.
|
|
314
|
+
function _tpScan(src, from, fn) {
|
|
315
|
+
let depth = 0;
|
|
316
|
+
for (let i = from; i < src.length; i++) {
|
|
317
|
+
const c = src[i];
|
|
318
|
+
if (c === '"' || c === "'") { for (i++; i < src.length && src[i] !== c; i++) if (src[i] === '\\') i++; continue; }
|
|
319
|
+
if (fn(i, c, depth)) return i;
|
|
320
|
+
if (c === '(' || c === '[') depth++;
|
|
321
|
+
else if (c === ')' || c === ']') depth--;
|
|
322
|
+
}
|
|
323
|
+
return -1;
|
|
278
324
|
}
|
|
325
|
+
// Split at top-level commas (outside quotes and brackets).
|
|
326
|
+
function _tpSplitArgs(inner) {
|
|
327
|
+
const out = []; let last = 0;
|
|
328
|
+
_tpScan(inner, 0, (i, c, d) => { if (c === ',' && d === 0) { out.push(inner.slice(last, i)); last = i + 1; } return false; });
|
|
329
|
+
out.push(inner.slice(last));
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
// Each IF( … )'s first argument goes through _tpGuardTest; nested IFs too.
|
|
333
|
+
function _tpRewriteIfTests(src) {
|
|
334
|
+
let out = '', i = 0;
|
|
335
|
+
const re = /\bIF\s*\(/g;
|
|
336
|
+
while (i < src.length) {
|
|
337
|
+
re.lastIndex = i;
|
|
338
|
+
let m = re.exec(src);
|
|
339
|
+
// skip a match inside quotes
|
|
340
|
+
while (m && _tpInQuotes(src, m.index)) { re.lastIndex = m.index + 1; m = re.exec(src); }
|
|
341
|
+
if (!m) { out += src.slice(i); break; }
|
|
342
|
+
const open = m.index + m[0].length - 1;
|
|
343
|
+
const close = _tpScan(src, open + 1, (j, c, d) => c === ')' && d === 0);
|
|
344
|
+
if (close < 0) { out += src.slice(i); break; } // unbalanced: the compiler says so
|
|
345
|
+
const args = _tpSplitArgs(src.slice(open + 1, close)).map(_tpRewriteIfTests);
|
|
346
|
+
if (args.length) args[0] = _tpGuardTest(args[0]);
|
|
347
|
+
out += src.slice(i, m.index) + 'IF(' + args.join(',') + ')';
|
|
348
|
+
i = close + 1;
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
function _tpInQuotes(src, at) {
|
|
353
|
+
let q = '';
|
|
354
|
+
for (let i = 0; i < at; i++) { const c = src[i]; if (q) { if (c === '\\') i++; else if (c === q) q = ''; } else if (c === '"' || c === "'") q = c; }
|
|
355
|
+
return !!q;
|
|
356
|
+
}
|
|
357
|
+
// A test's comparisons become _tpCmp((left), 'op', (right)); && / || and
|
|
358
|
+
// brackets are kept, == and != are left as they are.
|
|
359
|
+
function _tpGuardTest(test) {
|
|
360
|
+
const t = String(test);
|
|
361
|
+
const parts = []; let last = 0;
|
|
362
|
+
_tpScan(t, 0, (i, c, d) => {
|
|
363
|
+
if (d === 0 && ((c === '&' && t[i + 1] === '&') || (c === '|' && t[i + 1] === '|'))) { parts.push(t.slice(last, i), t.slice(i, i + 2)); last = i + 2; }
|
|
364
|
+
return false;
|
|
365
|
+
});
|
|
366
|
+
if (!parts.length) {
|
|
367
|
+
const s = t.trim(), lead = t.slice(0, t.indexOf(s)), tail = t.slice(t.indexOf(s) + s.length);
|
|
368
|
+
if (s[0] === '(' && _tpScan(s, 1, (j, c, d) => c === ')' && d === 0) === s.length - 1) return lead + '(' + _tpGuardTest(s.slice(1, -1)) + ')' + tail;
|
|
369
|
+
let at = -1, op = '';
|
|
370
|
+
_tpScan(t, 0, (i, c, d) => {
|
|
371
|
+
if (d !== 0 || (c !== '<' && c !== '>')) return false;
|
|
372
|
+
if (t[i + 1] === '=') { at = i; op = c + '='; return true; }
|
|
373
|
+
if (t[i - 1] === '=' || t[i + 1] === '>' || t[i + 1] === '<') return false;
|
|
374
|
+
at = i; op = c; return true;
|
|
375
|
+
});
|
|
376
|
+
return at < 0 ? t : `_tpCmp((${t.slice(0, at)}), '${op}', (${t.slice(at + op.length)}))`;
|
|
377
|
+
}
|
|
378
|
+
parts.push(t.slice(last));
|
|
379
|
+
return parts.map((p, k) => (k % 2 ? p : _tpGuardTest(p))).join('');
|
|
380
|
+
}
|
|
381
|
+
// A result is a number or text (49v). Text is trimmed; empty text is no value.
|
|
382
|
+
function _tpResult(v) {
|
|
383
|
+
if (typeof v === 'string') { const t = v.trim(); return t ? t : null; }
|
|
384
|
+
return v;
|
|
385
|
+
}
|
|
386
|
+
// Has a value to show: a finite number or non-empty text.
|
|
387
|
+
function _tpHasVal(v) { return Number.isFinite(v) || (typeof v === 'string' && v !== ''); }
|
|
388
|
+
function _tpIsText(v) { return typeof v === 'string' && v !== ''; }
|
|
279
389
|
|
|
280
390
|
// Same evaluation as _tpEvaluate but records a per-aggregate breakdown (each
|
|
281
391
|
// SUM/AVG/MIN/MAX/COUNT call, the rows it spanned, and each row's value) so the
|
|
@@ -303,7 +413,12 @@ function _tpTrace(formula, rows) {
|
|
|
303
413
|
const COUNT = (cf) => { const subset = filteredFor(cf); trace.push({ op: 'COUNT', terms: subset.map(r => ({ idx: safe.indexOf(r), label: rowLabel(r), value: 1 })), result: subset.length }); return subset.length; };
|
|
304
414
|
const _tpNum = x => (typeof x === 'number' ? x : (x == null || x === '' ? NaN : Number(x)));
|
|
305
415
|
let value = NaN;
|
|
306
|
-
|
|
416
|
+
const _tpHas = (field, lit) => {
|
|
417
|
+
const want = String(lit == null ? '' : lit).trim().toLowerCase();
|
|
418
|
+
const vals = Array.isArray(field) ? field : String(field == null ? '' : field).split('|');
|
|
419
|
+
return vals.some(v => String(v).trim().toLowerCase() === want);
|
|
420
|
+
};
|
|
421
|
+
try { value = _tpResult(fn(SUM, AVG, AVG, MIN, MAX, COUNT, Math.PI, Math.E, _tpNum, _tpHas, _tpIF, _tpCmp)); } catch (_) {}
|
|
307
422
|
return { value, trace };
|
|
308
423
|
}
|
|
309
424
|
|
|
@@ -350,7 +465,7 @@ function _tpSubstituteParamRefs(formula, valueMap) {
|
|
|
350
465
|
for (const r of refs) {
|
|
351
466
|
out += s.slice(cursor, r.start);
|
|
352
467
|
const v = valueMap[r.name.toLowerCase()];
|
|
353
|
-
out += '(' + (Number.isFinite(v) ? v : 'NaN') + ')';
|
|
468
|
+
out += '(' + (Number.isFinite(v) ? v : _tpIsText(v) ? JSON.stringify(v) : 'NaN') + ')';
|
|
354
469
|
cursor = r.end + 1;
|
|
355
470
|
}
|
|
356
471
|
return out + s.slice(cursor);
|
|
@@ -386,7 +501,7 @@ function _tpEvaluateAll(params, rows) {
|
|
|
386
501
|
const dr = resolve(dep);
|
|
387
502
|
if (dr.needsDensity) { needsDensity = dr.needsDensity; continue; }
|
|
388
503
|
if (dr.error) { depError = depError || `[${ref.name}] → ${dr.error}`; continue; }
|
|
389
|
-
if (!
|
|
504
|
+
if (!_tpHasVal(dr.value)) { depError = depError || `[${ref.name}] has no value`; continue; }
|
|
390
505
|
valueMap[key] = dr.value;
|
|
391
506
|
}
|
|
392
507
|
|
|
@@ -401,6 +516,9 @@ function _tpEvaluateAll(params, rows) {
|
|
|
401
516
|
try {
|
|
402
517
|
const substituted = _tpSubstituteParamRefs(p.formula, valueMap);
|
|
403
518
|
res = { value: _tpEvaluate(substituted, rows), error: '', name: p.name };
|
|
519
|
+
// Text is a claim (49w): none while an ingredient it reads, here or
|
|
520
|
+
// through a [Parameter], has no value ("Sugar free" from no data).
|
|
521
|
+
if (_tpIsText(res.value) && incomplete(p)) res = { value: null, error: '', name: p.name, held: true };
|
|
404
522
|
} catch (e) {
|
|
405
523
|
res = { value: null, error: e.message || 'eval error', name: p.name };
|
|
406
524
|
}
|
|
@@ -408,6 +526,20 @@ function _tpEvaluateAll(params, rows) {
|
|
|
408
526
|
delete visiting[p.id];
|
|
409
527
|
return (results[p.id] = res);
|
|
410
528
|
}
|
|
529
|
+
const _inc = {};
|
|
530
|
+
function incomplete(p, seen) {
|
|
531
|
+
if (p.id in _inc) return _inc[p.id];
|
|
532
|
+
seen = seen || new Set();
|
|
533
|
+
if (seen.has(p.id)) return false;
|
|
534
|
+
seen.add(p.id);
|
|
535
|
+
let out = false;
|
|
536
|
+
try { out = !!_tpMissingNote(_tpMissingInputs(p.formula, rows)); } catch (_) {}
|
|
537
|
+
if (!out) for (const ref of _tpScanParamRefs(p.formula)) {
|
|
538
|
+
const dep = byName[ref.name.toLowerCase()];
|
|
539
|
+
if (dep && dep.id !== p.id && incomplete(dep, seen)) { out = true; break; }
|
|
540
|
+
}
|
|
541
|
+
return (_inc[p.id] = out);
|
|
542
|
+
}
|
|
411
543
|
|
|
412
544
|
list.forEach(resolve);
|
|
413
545
|
return results;
|
|
@@ -842,7 +974,7 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
842
974
|
const k = rf.name.toLowerCase();
|
|
843
975
|
if (seenRef.has(k)) return; seenRef.add(k);
|
|
844
976
|
const v = valueMap[k];
|
|
845
|
-
refBits.push(`<code>[${esc(rf.name)}]</code> = <strong>${Number.isFinite(v) ? _tpFmtValue(v) : '<span style="color:var(--danger)">ERR</span>'}</strong>`);
|
|
977
|
+
refBits.push(`<code>[${esc(rf.name)}]</code> = <strong>${Number.isFinite(v) ? _tpFmtValue(v) : _tpIsText(v) ? esc(JSON.stringify(v)) : '<span style="color:var(--danger)">ERR</span>'}</strong>`);
|
|
846
978
|
});
|
|
847
979
|
const substituted = (typeof _tpSubstituteParamRefs === 'function') ? _tpSubstituteParamRefs(formula, valueMap) : formula;
|
|
848
980
|
let t = { value: NaN, trace: [] };
|
|
@@ -867,6 +999,9 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
867
999
|
} else {
|
|
868
1000
|
resultHtml = `<div style="font-size:12.5px;margin-top:8px">Value = <strong>${esc(_tpFmtValue(t.value))}</strong>${unit}</div>`;
|
|
869
1001
|
}
|
|
1002
|
+
} else if (_tpIsText(t.value)) {
|
|
1003
|
+
// A condition's text result (49v): the formula, then what it gave.
|
|
1004
|
+
resultHtml = `<div style="${mono};font-size:12.5px;margin-top:8px;color:var(--dk-text, #0f172a)">Value = ${esc(formula.replace(/\s+/g, ' ').trim())} = <strong>${esc(JSON.stringify(t.value))}</strong></div>`;
|
|
870
1005
|
}
|
|
871
1006
|
|
|
872
1007
|
// The table: only when the formula aggregates over rows.
|
|
@@ -1020,6 +1155,24 @@ function _tpMissingNote(miss) {
|
|
|
1020
1155
|
return parts.length ? { text: parts.join(' · '), tip: tips.join('\n') } : null;
|
|
1021
1156
|
}
|
|
1022
1157
|
|
|
1158
|
+
// A text result held back for missing values (49w): the gaps of the formula
|
|
1159
|
+
// itself, else of the first [Parameter] it reads that has them.
|
|
1160
|
+
function _tpHeldNote(p, params, rows) {
|
|
1161
|
+
const byName = {};
|
|
1162
|
+
(params || []).forEach(x => { if (x && x.name) byName[String(x.name).trim().toLowerCase()] = x; });
|
|
1163
|
+
const seen = new Set();
|
|
1164
|
+
const find = q => {
|
|
1165
|
+
if (!q || seen.has(q.id)) return null;
|
|
1166
|
+
seen.add(q.id);
|
|
1167
|
+
const own = _tpMissingNote(_tpMissingInputs(q.formula, rows));
|
|
1168
|
+
if (own) return q === p ? own : { text: `[${q.name}]: ${own.text}`, tip: own.tip };
|
|
1169
|
+
for (const ref of _tpScanParamRefs(q.formula)) { const n = find(byName[ref.name.toLowerCase()]); if (n) return n; }
|
|
1170
|
+
return null;
|
|
1171
|
+
};
|
|
1172
|
+
const n = find(p);
|
|
1173
|
+
return n ? { text: 'No result: ' + n.text, tip: n.tip + '\nA text result waits until every value it reads is there.' } : null;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1023
1176
|
function renderTheoreticalParamsHtml(entityType, entity) {
|
|
1024
1177
|
const params = _tpEffectiveParams(entityType, entity);
|
|
1025
1178
|
const { source, rows } = _tpEffectiveComposition(entityType, entity);
|
|
@@ -1057,7 +1210,7 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1057
1210
|
const evalAll = _tpEvaluateAll(params, evalRows);
|
|
1058
1211
|
// Name → resolved value, for the "Show calculation" panel's [Param] references.
|
|
1059
1212
|
const _tpValueMap = {};
|
|
1060
|
-
params.forEach(p => { const r = evalAll[p.id]; if (p.name && r && !r.error &&
|
|
1213
|
+
params.forEach(p => { const r = evalAll[p.id]; if (p.name && r && !r.error && _tpHasVal(r.value)) _tpValueMap[String(p.name).trim().toLowerCase()] = r.value; });
|
|
1061
1214
|
|
|
1062
1215
|
const rowsHtml = params.map(p => {
|
|
1063
1216
|
const r = evalAll[p.id] || { value: null, error: '' };
|
|
@@ -1065,12 +1218,12 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1065
1218
|
const errorText = r.error || '';
|
|
1066
1219
|
const valueStr = errorText
|
|
1067
1220
|
? `<span style="color:var(--danger)" title="${esc(errorText)}">ERR</span>`
|
|
1068
|
-
: (Number.isFinite(value) ? _tpFmtValue(value) : '—');
|
|
1221
|
+
: (Number.isFinite(value) ? _tpFmtValue(value) : _tpIsText(value) ? `<span class="tp-text-val" style="font-variant-numeric:normal">${esc(value)}</span>` : '—');
|
|
1069
1222
|
|
|
1070
|
-
// Pass/fail vs. spec, if defined
|
|
1223
|
+
// Pass/fail vs. spec, if defined (numbers only: a text result has no spec)
|
|
1071
1224
|
const pfBadge = (!errorText && Number.isFinite(value)) ? _tpSpecBadgeHtml(value, p.spec) : '';
|
|
1072
1225
|
|
|
1073
|
-
const miss = (!errorText &&
|
|
1226
|
+
const miss = (!errorText && _tpHasVal(value)) ? _tpMissingNote(_tpMissingInputs(p.formula, evalRows)) : r.held ? _tpHeldNote(p, params, evalRows) : (r.needsDensity ? _tpNeedsDensityNote(r.needsDensity) : null);
|
|
1074
1227
|
const missHtml = miss ? `<div class="tp-miss" title="${esc(miss.tip)}" style="margin-top:3px;font-size:11px;font-weight:400;color:var(--dk-amber-fg, #b45309);cursor:help">⚠ ${esc(miss.text)}</div>` : '';
|
|
1075
1228
|
|
|
1076
1229
|
const formulaPreview = (p.formula || '').length > 80
|
|
@@ -1085,14 +1238,14 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1085
1238
|
<td style="padding:8px 12px;text-align:center">${pfBadge}</td>
|
|
1086
1239
|
<td style="padding:8px 12px;font-family:ui-monospace,monospace;font-size:11px;color:var(--dk-text-3, #475569)" title="${esc(p.formula || '')}">
|
|
1087
1240
|
<span>${formulaPreview}</span>
|
|
1088
|
-
${(!errorText &&
|
|
1241
|
+
${(!errorText && _tpHasVal(value)) ? `<button onclick="_tpToggleCalc('${p.id}')" title="Show how this value was calculated" style="margin-left:8px;font-family:inherit;font-size:10px;padding:1px 7px;background:var(--dk-blue-bg, #eff6ff);border:1px solid var(--dk-blue-line, #bfdbfe);color:var(--dk-blue-fg, #1e40af);border-radius:9999px;cursor:pointer;white-space:nowrap">Show calc</button>` : ''}
|
|
1089
1242
|
</td>
|
|
1090
1243
|
<td style="padding:8px 12px;text-align:right;white-space:nowrap">
|
|
1091
1244
|
<button class="btn btn-secondary btn-sm btn-icon" onclick="openTheoreticalParamModal('${entityType}','${entity.id}','${p.id}')" title="Edit">${typeof ICON !== 'undefined' && ICON.edit ? ICON.edit : '✎'}</button>
|
|
1092
1245
|
<button class="btn btn-danger btn-sm btn-icon" onclick="confirmDeleteTheoreticalParam('${entityType}','${entity.id}','${p.id}','${escJsAttr(p.name||'')}')"><span class="fl-cross" aria-hidden="true"></span></button>
|
|
1093
1246
|
</td>
|
|
1094
1247
|
</tr>
|
|
1095
|
-
${(!errorText &&
|
|
1248
|
+
${(!errorText && _tpHasVal(value)) ? `<tr id="tp-calc-${p.id}" style="display:none"><td colspan="5" style="padding:0">${_tpCalcHtml(p, evalRows, _tpValueMap)}</td></tr>` : ''}`;
|
|
1096
1249
|
}).join('');
|
|
1097
1250
|
|
|
1098
1251
|
const tableHtml = params.length ? `
|
|
@@ -1147,7 +1300,7 @@ function _tpPinnedChipsHtml(entityType, entity) {
|
|
|
1147
1300
|
const r = evalAll[p.id] || { value: null, error: '' };
|
|
1148
1301
|
const valueStr = r.error
|
|
1149
1302
|
? 'ERR'
|
|
1150
|
-
: (Number.isFinite(r.value) ? _tpFmtValue(r.value) : '—');
|
|
1303
|
+
: (Number.isFinite(r.value) ? _tpFmtValue(r.value) : _tpIsText(r.value) ? r.value : '—');
|
|
1151
1304
|
// Spec tint (matches the table's pass/fail badge colours)
|
|
1152
1305
|
let bg = 'var(--dk-raised, #f1f5f9)', fg = 'var(--dk-text-2, #334155)', bd = 'var(--dk-line-soft, #e2e8f0)';
|
|
1153
1306
|
if (!r.error && Number.isFinite(r.value) && p.spec) {
|
|
@@ -1156,7 +1309,7 @@ function _tpPinnedChipsHtml(entityType, entity) {
|
|
|
1156
1309
|
if (okMin && okMax) { bg = 'var(--dk-green-bg2, #dcfce7)'; fg = 'var(--dk-green-fg, #15803d)'; bd = 'var(--dk-green-line, #bbf7d0)'; }
|
|
1157
1310
|
else { bg = 'var(--dk-red-bg2, #fee2e2)'; fg = 'var(--dk-red-fg, #b91c1c)'; bd = 'var(--dk-red-line, #fecaca)'; }
|
|
1158
1311
|
} else if (r.error) { fg = 'var(--dk-red-fg, #b91c1c)'; }
|
|
1159
|
-
const miss = (!r.error &&
|
|
1312
|
+
const miss = (!r.error && _tpHasVal(r.value)) ? _tpMissingNote(_tpMissingInputs(p.formula, chipRows)) : r.held ? _tpHeldNote(p, allParams, chipRows) : (r.needsDensity ? _tpNeedsDensityNote(r.needsDensity) : null);
|
|
1160
1313
|
const title = r.error ? r.error : ((p.description || `${p.name}${p.unit ? ' (' + p.unit + ')' : ''}`) + (miss ? '\n⚠ ' + miss.text + '\n' + miss.tip : ''));
|
|
1161
1314
|
return `<span title="${esc(title)}" style="display:inline-flex;align-items:baseline;gap:5px;padding:3px 9px;border-radius:9999px;background:${bg};border:1px solid ${bd};font-size:11.5px;line-height:1.4;white-space:nowrap">
|
|
1162
1315
|
<span style="color:var(--dk-muted, #64748b)">${esc(p.name)}</span>
|
|
@@ -1244,7 +1397,8 @@ function _tpFieldPaletteHtml(evalRows, params, currentParamId) {
|
|
|
1244
1397
|
// Aggregations — the wrapper a row/ing field must sit inside.
|
|
1245
1398
|
const aggs = ['SUM', 'AVG', 'MIN', 'MAX', 'COUNT']
|
|
1246
1399
|
.map(a => chip(`${a}()`, `${a}()`, `${a} across all ingredient rows`)).join('')
|
|
1247
|
-
+ chip('WHERE', 'WHERE', 'Keep only some rows, e.g. SUM(row.amount) WHERE ing.purity > 0')
|
|
1400
|
+
+ chip('WHERE', 'WHERE', 'Keep only some rows, e.g. SUM(row.amount) WHERE ing.purity > 0')
|
|
1401
|
+
+ chip('IF()', 'IF()', "IF(test, then, else): a number or text by a condition, e.g. IF([VOC] < 50, 'Low VOC', 'Standard')");
|
|
1248
1402
|
|
|
1249
1403
|
// Row fields — always available.
|
|
1250
1404
|
const rowChips = [
|
|
@@ -1431,7 +1585,7 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1431
1585
|
if (!nm) return;
|
|
1432
1586
|
knownParamNames.add(nm);
|
|
1433
1587
|
const r = otherResults[p.id];
|
|
1434
|
-
if (r &&
|
|
1588
|
+
if (r && _tpHasVal(r.value)) paramValueMap[nm] = r.value;
|
|
1435
1589
|
});
|
|
1436
1590
|
const unknownRefs = _tpScanParamRefs(formula)
|
|
1437
1591
|
.map(r => r.name)
|
|
@@ -1445,7 +1599,11 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1445
1599
|
wrap.innerHTML = `<div style="color:var(--danger);font-size:12.5px"><strong>Can’t compute yet:</strong> ${esc(e.message)}</div>`;
|
|
1446
1600
|
return;
|
|
1447
1601
|
}
|
|
1448
|
-
|
|
1602
|
+
// A text result waits for every value it reads (49w), as in the saved table.
|
|
1603
|
+
const held = _tpIsText(result) && (ingMissingFields.size > 0
|
|
1604
|
+
|| _tpScanParamRefs(formula).some(ref => { const q = otherParams.find(x => String(x.name || '').trim().toLowerCase() === ref.name.toLowerCase()); const rr = q && otherResults[q.id]; return !!(rr && (rr.held || (_tpHasVal(rr.value) && _tpMissingNote(_tpMissingInputs(q.formula, evalRows))))); }));
|
|
1605
|
+
if (held) result = null;
|
|
1606
|
+
const valueStr = Number.isFinite(result) ? _tpFmtValue(result) : _tpIsText(result) ? result : (result == null || typeof result === 'number' ? '—' : String(result));
|
|
1449
1607
|
const unit = (document.getElementById('tp-unit')?.value || '').trim();
|
|
1450
1608
|
const sourceChip = entityType === 'batch'
|
|
1451
1609
|
? `<span style="color:var(--text-muted);font-size:11px;margin-left:6px">on ${source === 'actual' ? 'actual composition' : 'formula proposal'}</span>`
|
|
@@ -1475,6 +1633,7 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1475
1633
|
${sourceChip}
|
|
1476
1634
|
</div>
|
|
1477
1635
|
<div style="margin-top:5px;color:var(--text-muted);font-size:11.5px">Evaluated over ${evalRows.length} composition row${evalRows.length===1?'':'s'}.</div>
|
|
1636
|
+
${held ? `<div style="margin-top:6px;color:var(--dk-amber-fg, #d97706);font-size:11.5px"><span class="fl-warn" aria-hidden="true"></span> No text result until every value it reads is there. Enter 0 where an ingredient truly has none.</div>` : ''}
|
|
1478
1637
|
${missingHtml}
|
|
1479
1638
|
${unknownRefHtml}
|
|
1480
1639
|
`;
|
|
@@ -1531,6 +1690,15 @@ function _tpPresetCatalog() {
|
|
|
1531
1690
|
formula: "100 * SUM(row.amount * ing.solids) / (100 * SUM(row.amount))",
|
|
1532
1691
|
description: 'Same as NV but rescaled to 0–100 if ing.solids is stored as fraction (0–1).',
|
|
1533
1692
|
},
|
|
1693
|
+
// Conditions (49v): IF gives text by a threshold. Each works out its own number, so it
|
|
1694
|
+
// needs no other parameter; change the limits to your own.
|
|
1695
|
+
{
|
|
1696
|
+
group: 'Coatings',
|
|
1697
|
+
name: 'VOC class',
|
|
1698
|
+
unit: '',
|
|
1699
|
+
formula: "IF(1000 * SUM(row.amount * ing.volatileOrganic) / SUM(row.amount * ing.volume) <= 50, 'Low VOC', 'Standard')",
|
|
1700
|
+
description: 'Low VOC at 50 g/L or less, else Standard. Set the limit your market uses. Needs ing.density on every row.',
|
|
1701
|
+
},
|
|
1534
1702
|
// ---- Reactive (js/reactive.js; Jun 27 Oct: an index everywhere, acid counts toward the NCO demand) ----
|
|
1535
1703
|
// ing.epoxy … ing.vinyl are meq/g from each ingredient's Reactive groups (0 when it has none). The formula's
|
|
1536
1704
|
// Composition tab shows the same numbers in its balance strip.
|
|
@@ -1541,6 +1709,13 @@ function _tpPresetCatalog() {
|
|
|
1541
1709
|
formula: '100 * SUM(row.amount * ing.amineH) / SUM(row.amount * ing.epoxy)',
|
|
1542
1710
|
description: 'Amine H equivalents per 100 epoxy equivalents; 100 = stoichiometric. From each ingredient’s Reactive groups (EEW, AHEW).',
|
|
1543
1711
|
},
|
|
1712
|
+
{
|
|
1713
|
+
group: 'Reactive',
|
|
1714
|
+
name: 'Mix ratio check',
|
|
1715
|
+
unit: '',
|
|
1716
|
+
formula: "IF(100 * SUM(row.amount * ing.amineH) / SUM(row.amount * ing.epoxy) < 95, 'Amine short', IF(100 * SUM(row.amount * ing.amineH) / SUM(row.amount * ing.epoxy) > 105, 'Amine excess', 'On ratio'))",
|
|
1717
|
+
description: 'On ratio for an amine H : epoxy index of 95 to 105, else which side is off. Same groups as the index.',
|
|
1718
|
+
},
|
|
1544
1719
|
{
|
|
1545
1720
|
group: 'Reactive',
|
|
1546
1721
|
name: 'Isocyanate index',
|
|
@@ -1605,6 +1780,13 @@ function _tpPresetCatalog() {
|
|
|
1605
1780
|
formula: "SUM(row.amount * ing.hlb WHERE ing.hlb) / SUM(row.amount WHERE ing.hlb)",
|
|
1606
1781
|
description: 'Weight-average HLB of the emulsifier blend (only rows that carry an HLB count). Match it to the oil phase\'s required HLB. Needs ing.hlb (Surfactant details, 0–20).',
|
|
1607
1782
|
},
|
|
1783
|
+
{
|
|
1784
|
+
group: 'Surfactants',
|
|
1785
|
+
name: 'Emulsion type',
|
|
1786
|
+
unit: '',
|
|
1787
|
+
formula: "IF(SUM(row.amount * ing.hlb WHERE ing.hlb) / SUM(row.amount WHERE ing.hlb) <= 6, 'W/O (water in oil)', IF(SUM(row.amount * ing.hlb WHERE ing.hlb) / SUM(row.amount WHERE ing.hlb) >= 8, 'O/W (oil in water)', 'Between W/O and O/W'))",
|
|
1788
|
+
description: 'What the blend HLB favors: 3 to 6 water in oil, 8 to 18 oil in water. Needs ing.hlb.',
|
|
1789
|
+
},
|
|
1608
1790
|
// ---- Food & nutrition ----
|
|
1609
1791
|
// Per 100 g of product: Σ(row wt% × ingredient value per 100 g) / Σ(row wt%).
|
|
1610
1792
|
// Dividing by SUM(row.amount), not 100, keeps it right when the rows don't
|
|
@@ -1665,6 +1847,27 @@ function _tpPresetCatalog() {
|
|
|
1665
1847
|
formula: '2.5 * SUM(row.amount * ing.sodium) / SUM(row.amount) / 1000',
|
|
1666
1848
|
description: 'Salt equivalent as on EU labels: sodium × 2.5, in g/100g. Needs ing.sodium in mg/100g.',
|
|
1667
1849
|
},
|
|
1850
|
+
{
|
|
1851
|
+
group: 'Food & nutrition',
|
|
1852
|
+
name: 'Sugar claim',
|
|
1853
|
+
unit: '',
|
|
1854
|
+
formula: "IF(SUM(row.amount * ing.sugar) / SUM(row.amount) <= 0.5, 'Sugar free', IF(SUM(row.amount * ing.sugar) / SUM(row.amount) <= 5, 'Low sugar', 'No sugar claim'))",
|
|
1855
|
+
description: 'EU limits for solids: sugar free at 0.5 g/100g or less, low sugar at 5. Drinks use 2.5 g/100 mL for low sugar. Needs ing.sugar.',
|
|
1856
|
+
},
|
|
1857
|
+
{
|
|
1858
|
+
group: 'Food & nutrition',
|
|
1859
|
+
name: 'Salt claim',
|
|
1860
|
+
unit: '',
|
|
1861
|
+
formula: "IF(SUM(row.amount * ing.sodium) / SUM(row.amount) <= 5, 'Salt free', IF(SUM(row.amount * ing.sodium) / SUM(row.amount) <= 40, 'Very low salt', IF(SUM(row.amount * ing.sodium) / SUM(row.amount) <= 120, 'Low salt', 'No salt claim')))",
|
|
1862
|
+
description: 'EU limits by sodium: 5, 40 and 120 mg/100g for salt free, very low and low. Needs ing.sodium in mg/100g.',
|
|
1863
|
+
},
|
|
1864
|
+
{
|
|
1865
|
+
group: 'Food & nutrition',
|
|
1866
|
+
name: 'Protein claim',
|
|
1867
|
+
unit: '',
|
|
1868
|
+
formula: "IF(4 * SUM(row.amount * ing.protein) >= 0.2 * SUM(row.amount * (4 * ing.protein + 4 * ing.carb + 9 * ing.fat)), 'High protein', IF(4 * SUM(row.amount * ing.protein) >= 0.12 * SUM(row.amount * (4 * ing.protein + 4 * ing.carb + 9 * ing.fat)), 'Source of protein', 'No protein claim'))",
|
|
1869
|
+
description: 'EU: high protein when protein gives 20% of the energy, source of protein at 12%. Needs ing.protein, ing.carb and ing.fat.',
|
|
1870
|
+
},
|
|
1668
1871
|
// ---- General ----
|
|
1669
1872
|
{
|
|
1670
1873
|
group: 'General',
|