formlab-mcp 0.6.72 → 0.6.74
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/cost.js +2 -2
- package/vendor/theoretical-params.js +299 -23
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.74",
|
|
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.74",
|
|
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.74",
|
|
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: {
|
package/vendor/cost.js
CHANGED
|
@@ -2646,9 +2646,9 @@ function openCostOverrideModal(kind, id) {
|
|
|
2646
2646
|
Computed cost is <strong>${compStr}</strong>. Enter a manual override to record the actual cost — it'll be flagged on the detail page whenever it diverges from the live computed value.
|
|
2647
2647
|
</p>
|
|
2648
2648
|
<label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px">Override (${esc(ccy)})</label>
|
|
2649
|
-
<input id="cost-ov-input" type="number" step="any" value="${esc(String(cur))}" placeholder="${computed != null ? (+computed).toPrecision(4) : ''}" style="width:100%;padding:7px 9px;border:1px solid var(--border);border-radius:
|
|
2649
|
+
<input id="cost-ov-input" type="number" step="any" value="${esc(String(cur))}" placeholder="${computed != null ? (+computed).toPrecision(4) : ''}" style="width:100%;padding:7px 9px;border:1px solid var(--border);border-radius:10px;font-size:14px" autofocus />
|
|
2650
2650
|
<label style="font-size:12px;font-weight:600;display:block;margin:12px 0 4px">Reason <span style="font-weight:400;color:var(--text-muted)">(optional)</span></label>
|
|
2651
|
-
<input id="cost-ov-note" type="text" value="${esc(String(curNote))}" placeholder="e.g. actual lot price incl. freight & MOQ" style="width:100%;padding:7px 9px;border:1px solid var(--border);border-radius:
|
|
2651
|
+
<input id="cost-ov-note" type="text" value="${esc(String(curNote))}" placeholder="e.g. actual lot price incl. freight & MOQ" style="width:100%;padding:7px 9px;border:1px solid var(--border);border-radius:10px;font-size:13px" />
|
|
2652
2652
|
<p style="font-size:11.5px;color:var(--text-muted);margin-top:8px">Leave the override blank and save to clear it (and its reason) and fall back to the computed cost.</p>`;
|
|
2653
2653
|
showModal(`${kind === 'sample' ? 'Sample' : 'Batch'} cost override`, body, () => _saveCostOverride(kind, id));
|
|
2654
2654
|
}
|
|
@@ -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;
|
|
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;
|
|
278
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;
|
|
@@ -487,10 +619,71 @@ function _tpBuildRows(composition) {
|
|
|
487
619
|
Object.defineProperty(rows, 'needsDensity', { value: [...new Set(noDensity)], enumerable: false });
|
|
488
620
|
}
|
|
489
621
|
}
|
|
622
|
+
_tpHarmonizeUnits(rows);
|
|
490
623
|
rows.forEach(r => { delete r._srcIng; delete r._srcSub; });
|
|
491
624
|
return rows;
|
|
492
625
|
}
|
|
493
626
|
|
|
627
|
+
// One unit per field before any formula reads it (49z). Custom fields are
|
|
628
|
+
// typed per ingredient, so sodium in mg/100g on one and g/100g on another was
|
|
629
|
+
// off by 1000× (17g only flagged it). Within a family the value is converted:
|
|
630
|
+
// mass per mass (%, g/100g, mg/100g, g/kg, mg/kg, ppm, ppb …) and energy per
|
|
631
|
+
// mass (kcal/100g, kJ/100g …). The target is the field's usual unit when the
|
|
632
|
+
// presets read it in one (sodium mg/100g, protein g/100g, solids %), else the
|
|
633
|
+
// unit most of these rows already use. Rows with no unit are left as they are;
|
|
634
|
+
// units from different families stay mixed and are still flagged.
|
|
635
|
+
// Same starters as js/views/ingredients.js CUSTOM_FIELD_STARTERS.
|
|
636
|
+
const _TP_USUAL_UNIT = { protein: 'g/100g', carb: 'g/100g', fat: 'g/100g', sugar: 'g/100g', fiber: 'g/100g', sodium: 'mg/100g', solids: '%' };
|
|
637
|
+
const _TP_UNIT_FAMILY = {
|
|
638
|
+
// grams of the thing per gram of ingredient
|
|
639
|
+
'%': ['m', 0.01], 'wt%': ['m', 0.01], '%w/w': ['m', 0.01], 'w/w%': ['m', 0.01], 'w/w': ['m', 0.01], 'g/100g': ['m', 0.01],
|
|
640
|
+
'mg/100g': ['m', 1e-5], 'µg/100g': ['m', 1e-8], 'g/kg': ['m', 1e-3], 'mg/g': ['m', 1e-3], 'g/g': ['m', 1],
|
|
641
|
+
'mg/kg': ['m', 1e-6], 'µg/g': ['m', 1e-6], 'ppm': ['m', 1e-6], 'µg/kg': ['m', 1e-9], 'ppb': ['m', 1e-9],
|
|
642
|
+
// kJ per gram
|
|
643
|
+
'kj/g': ['e', 1], 'kj/100g': ['e', 0.01], 'kj/kg': ['e', 0.001], 'kcal/g': ['e', 4.184], 'kcal/100g': ['e', 0.04184], 'kcal/kg': ['e', 0.004184], 'cal/g': ['e', 0.004184],
|
|
644
|
+
};
|
|
645
|
+
function _tpUnitKey(u) {
|
|
646
|
+
return String(u || '').trim().toLowerCase().replace(/\s+/g, '').replace(/^(mc|u)g/, 'µg').replace(/\/(mc|u)g/, '/µg');
|
|
647
|
+
}
|
|
648
|
+
function _tpUnitFactor(u) { return _TP_UNIT_FAMILY[_tpUnitKey(u)] || null; }
|
|
649
|
+
function _tpHarmonizeUnits(rows) {
|
|
650
|
+
const fields = new Set();
|
|
651
|
+
rows.forEach(r => Object.keys(r._cfUnits || {}).forEach(k => fields.add(k)));
|
|
652
|
+
const done = [];
|
|
653
|
+
fields.forEach(lk => {
|
|
654
|
+
const withUnit = rows.filter(r => r._cfUnits && r._cfUnits[lk] && r.ing && typeof r.ing[lk] === 'number' && Number.isFinite(r.ing[lk]));
|
|
655
|
+
const units = [...new Set(withUnit.map(r => r._cfUnits[lk]))];
|
|
656
|
+
if (units.length < 2) return;
|
|
657
|
+
// One unit, two spellings (ug/100g, µg/100g): one label, nothing to convert.
|
|
658
|
+
if (new Set(units.map(_tpUnitKey)).size < 2) { withUnit.forEach(r => { r._cfUnits[lk] = units[0]; }); return; }
|
|
659
|
+
const fams = new Set(units.map(u => (_tpUnitFactor(u) || ['?' + u])[0]));
|
|
660
|
+
if (fams.size !== 1 || [...fams][0][0] === '?') return; // not one convertible family: stays flagged
|
|
661
|
+
const usual = _TP_USUAL_UNIT[lk];
|
|
662
|
+
let target = usual && _tpUnitFactor(usual) && _tpUnitFactor(usual)[0] === [...fams][0] ? usual : null;
|
|
663
|
+
if (!target) {
|
|
664
|
+
// Counted by unit, not spelling (ug/100g = µg/100g); the unit's own spelling wins a tie.
|
|
665
|
+
const n = {}, order = [];
|
|
666
|
+
withUnit.forEach(r => { const k = _tpUnitKey(r._cfUnits[lk]); if (!(k in n)) { n[k] = 0; order.push(k); } n[k]++; });
|
|
667
|
+
const key = order.slice().sort((a, b) => (n[b] - n[a]) || order.indexOf(a) - order.indexOf(b))[0];
|
|
668
|
+
const spell = units.filter(u => _tpUnitKey(u) === key);
|
|
669
|
+
target = spell.find(u => u.replace(/\s+/g, '') === key) || spell[0];
|
|
670
|
+
}
|
|
671
|
+
const tf = _tpUnitFactor(target)[1];
|
|
672
|
+
const moved = [];
|
|
673
|
+
withUnit.forEach(r => {
|
|
674
|
+
const u = r._cfUnits[lk];
|
|
675
|
+
if (_tpUnitKey(u) === _tpUnitKey(target)) { r._cfUnits[lk] = target; return; }
|
|
676
|
+
const key = Object.keys(r.ing).find(k => k.toLowerCase() === lk);
|
|
677
|
+
if (!key) return;
|
|
678
|
+
r.ing[key] = +(r.ing[key] * _tpUnitFactor(u)[1] / tf).toPrecision(12);
|
|
679
|
+
r._cfUnits[lk] = target;
|
|
680
|
+
moved.push({ name: r.ing._isSubFormula ? (r._subName || 'sub-formula') : (r.ing.name || '(unnamed)'), from: u });
|
|
681
|
+
});
|
|
682
|
+
if (moved.length) done.push({ field: lk, to: target, rows: moved });
|
|
683
|
+
});
|
|
684
|
+
if (done.length) Object.defineProperty(rows, 'unitConversions', { value: done, enumerable: false, configurable: true });
|
|
685
|
+
}
|
|
686
|
+
|
|
494
687
|
// A premix's fields for its row in the parent (Jun, 28 Oct: "yes to per-field rules"). A field rolls up as the
|
|
495
688
|
// mass-weighted mean over the premix's rows when it adds by mass: a custom field in a per-mass unit (%, g/100 g,
|
|
496
689
|
// mg/kg, ppm, mg KOH/g …), or a known per-mass name with no unit (solids, NV %, protein, fat …). Only when every row
|
|
@@ -833,6 +1026,17 @@ function _tpReplaceSpans(formula, spans, repl) {
|
|
|
833
1026
|
spans.forEach((sp, k) => { out += formula.slice(cur, sp.start) + repl(k); cur = sp.end; });
|
|
834
1027
|
return out + formula.slice(cur);
|
|
835
1028
|
}
|
|
1029
|
+
// "sodium: 2 rows in g/100g read as mg/100g" under Show calc, for the fields this formula reads (49z).
|
|
1030
|
+
function _tpConvNoteHtml(formula, rows) {
|
|
1031
|
+
const conv = rows && rows.unitConversions;
|
|
1032
|
+
if (!conv || !conv.length) return '';
|
|
1033
|
+
const used = new Set(_tpFieldRefs(formula));
|
|
1034
|
+
const lines = conv.filter(c => used.has(c.field)).map(c => {
|
|
1035
|
+
const from = [...new Set(c.rows.map(r => r.from))].join(', ');
|
|
1036
|
+
return `<span title="${esc(c.rows.map(r => `${r.name}: ${r.from} → ${c.to}`).join('\n'))}">${esc(c.field)}: ${c.rows.length} row${c.rows.length === 1 ? '' : 's'} in ${esc(from)} read as ${esc(c.to)}</span>`;
|
|
1037
|
+
});
|
|
1038
|
+
return lines.length ? `<div class="tp-conv-note" style="margin-top:6px;font-size:11.5px;color:var(--text-muted)">Units converted: ${lines.join(' · ')}</div>` : '';
|
|
1039
|
+
}
|
|
836
1040
|
function _tpCalcHtml(p, evalRows, valueMap) {
|
|
837
1041
|
const formula = String(p.formula || '');
|
|
838
1042
|
const refs = (typeof _tpScanParamRefs === 'function') ? _tpScanParamRefs(formula) : [];
|
|
@@ -842,7 +1046,7 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
842
1046
|
const k = rf.name.toLowerCase();
|
|
843
1047
|
if (seenRef.has(k)) return; seenRef.add(k);
|
|
844
1048
|
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>`);
|
|
1049
|
+
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
1050
|
});
|
|
847
1051
|
const substituted = (typeof _tpSubstituteParamRefs === 'function') ? _tpSubstituteParamRefs(formula, valueMap) : formula;
|
|
848
1052
|
let t = { value: NaN, trace: [] };
|
|
@@ -867,6 +1071,9 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
867
1071
|
} else {
|
|
868
1072
|
resultHtml = `<div style="font-size:12.5px;margin-top:8px">Value = <strong>${esc(_tpFmtValue(t.value))}</strong>${unit}</div>`;
|
|
869
1073
|
}
|
|
1074
|
+
} else if (_tpIsText(t.value)) {
|
|
1075
|
+
// A condition's text result (49v): the formula, then what it gave.
|
|
1076
|
+
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
1077
|
}
|
|
871
1078
|
|
|
872
1079
|
// The table: only when the formula aggregates over rows.
|
|
@@ -932,6 +1139,7 @@ function _tpCalcHtml(p, evalRows, valueMap) {
|
|
|
932
1139
|
return `<div style="padding:12px 14px;background:var(--dk-subtle, #f8fafc);border-top:1px solid var(--dk-line-soft, #e2e8f0);font-size:12px;color:var(--text);overflow-x:auto">
|
|
933
1140
|
${refBits.length ? `<div style="font-size:11.5px;color:var(--text-muted);margin-bottom:6px">References: ${refBits.join(' · ')}</div>` : ''}
|
|
934
1141
|
${tableHtml || (refBits.length ? '' : '<div style="color:var(--text-muted);font-size:11px">Value comes straight from the expression (no row aggregation).</div>')}
|
|
1142
|
+
${_tpConvNoteHtml(formula, evalRows)}
|
|
935
1143
|
${resultHtml}
|
|
936
1144
|
</div>`;
|
|
937
1145
|
}
|
|
@@ -1020,6 +1228,24 @@ function _tpMissingNote(miss) {
|
|
|
1020
1228
|
return parts.length ? { text: parts.join(' · '), tip: tips.join('\n') } : null;
|
|
1021
1229
|
}
|
|
1022
1230
|
|
|
1231
|
+
// A text result held back for missing values (49w): the gaps of the formula
|
|
1232
|
+
// itself, else of the first [Parameter] it reads that has them.
|
|
1233
|
+
function _tpHeldNote(p, params, rows) {
|
|
1234
|
+
const byName = {};
|
|
1235
|
+
(params || []).forEach(x => { if (x && x.name) byName[String(x.name).trim().toLowerCase()] = x; });
|
|
1236
|
+
const seen = new Set();
|
|
1237
|
+
const find = q => {
|
|
1238
|
+
if (!q || seen.has(q.id)) return null;
|
|
1239
|
+
seen.add(q.id);
|
|
1240
|
+
const own = _tpMissingNote(_tpMissingInputs(q.formula, rows));
|
|
1241
|
+
if (own) return q === p ? own : { text: `[${q.name}]: ${own.text}`, tip: own.tip };
|
|
1242
|
+
for (const ref of _tpScanParamRefs(q.formula)) { const n = find(byName[ref.name.toLowerCase()]); if (n) return n; }
|
|
1243
|
+
return null;
|
|
1244
|
+
};
|
|
1245
|
+
const n = find(p);
|
|
1246
|
+
return n ? { text: 'No result: ' + n.text, tip: n.tip + '\nA text result waits until every value it reads is there.' } : null;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1023
1249
|
function renderTheoreticalParamsHtml(entityType, entity) {
|
|
1024
1250
|
const params = _tpEffectiveParams(entityType, entity);
|
|
1025
1251
|
const { source, rows } = _tpEffectiveComposition(entityType, entity);
|
|
@@ -1057,7 +1283,7 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1057
1283
|
const evalAll = _tpEvaluateAll(params, evalRows);
|
|
1058
1284
|
// Name → resolved value, for the "Show calculation" panel's [Param] references.
|
|
1059
1285
|
const _tpValueMap = {};
|
|
1060
|
-
params.forEach(p => { const r = evalAll[p.id]; if (p.name && r && !r.error &&
|
|
1286
|
+
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
1287
|
|
|
1062
1288
|
const rowsHtml = params.map(p => {
|
|
1063
1289
|
const r = evalAll[p.id] || { value: null, error: '' };
|
|
@@ -1065,12 +1291,12 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1065
1291
|
const errorText = r.error || '';
|
|
1066
1292
|
const valueStr = errorText
|
|
1067
1293
|
? `<span style="color:var(--danger)" title="${esc(errorText)}">ERR</span>`
|
|
1068
|
-
: (Number.isFinite(value) ? _tpFmtValue(value) : '—');
|
|
1294
|
+
: (Number.isFinite(value) ? _tpFmtValue(value) : _tpIsText(value) ? `<span class="tp-text-val" style="font-variant-numeric:normal">${esc(value)}</span>` : '—');
|
|
1069
1295
|
|
|
1070
|
-
// Pass/fail vs. spec, if defined
|
|
1296
|
+
// Pass/fail vs. spec, if defined (numbers only: a text result has no spec)
|
|
1071
1297
|
const pfBadge = (!errorText && Number.isFinite(value)) ? _tpSpecBadgeHtml(value, p.spec) : '';
|
|
1072
1298
|
|
|
1073
|
-
const miss = (!errorText &&
|
|
1299
|
+
const miss = (!errorText && _tpHasVal(value)) ? _tpMissingNote(_tpMissingInputs(p.formula, evalRows)) : r.held ? _tpHeldNote(p, params, evalRows) : (r.needsDensity ? _tpNeedsDensityNote(r.needsDensity) : null);
|
|
1074
1300
|
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
1301
|
|
|
1076
1302
|
const formulaPreview = (p.formula || '').length > 80
|
|
@@ -1085,14 +1311,14 @@ function renderTheoreticalParamsHtml(entityType, entity) {
|
|
|
1085
1311
|
<td style="padding:8px 12px;text-align:center">${pfBadge}</td>
|
|
1086
1312
|
<td style="padding:8px 12px;font-family:ui-monospace,monospace;font-size:11px;color:var(--dk-text-3, #475569)" title="${esc(p.formula || '')}">
|
|
1087
1313
|
<span>${formulaPreview}</span>
|
|
1088
|
-
${(!errorText &&
|
|
1314
|
+
${(!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
1315
|
</td>
|
|
1090
1316
|
<td style="padding:8px 12px;text-align:right;white-space:nowrap">
|
|
1091
1317
|
<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
1318
|
<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
1319
|
</td>
|
|
1094
1320
|
</tr>
|
|
1095
|
-
${(!errorText &&
|
|
1321
|
+
${(!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
1322
|
}).join('');
|
|
1097
1323
|
|
|
1098
1324
|
const tableHtml = params.length ? `
|
|
@@ -1147,7 +1373,7 @@ function _tpPinnedChipsHtml(entityType, entity) {
|
|
|
1147
1373
|
const r = evalAll[p.id] || { value: null, error: '' };
|
|
1148
1374
|
const valueStr = r.error
|
|
1149
1375
|
? 'ERR'
|
|
1150
|
-
: (Number.isFinite(r.value) ? _tpFmtValue(r.value) : '—');
|
|
1376
|
+
: (Number.isFinite(r.value) ? _tpFmtValue(r.value) : _tpIsText(r.value) ? r.value : '—');
|
|
1151
1377
|
// Spec tint (matches the table's pass/fail badge colours)
|
|
1152
1378
|
let bg = 'var(--dk-raised, #f1f5f9)', fg = 'var(--dk-text-2, #334155)', bd = 'var(--dk-line-soft, #e2e8f0)';
|
|
1153
1379
|
if (!r.error && Number.isFinite(r.value) && p.spec) {
|
|
@@ -1156,7 +1382,7 @@ function _tpPinnedChipsHtml(entityType, entity) {
|
|
|
1156
1382
|
if (okMin && okMax) { bg = 'var(--dk-green-bg2, #dcfce7)'; fg = 'var(--dk-green-fg, #15803d)'; bd = 'var(--dk-green-line, #bbf7d0)'; }
|
|
1157
1383
|
else { bg = 'var(--dk-red-bg2, #fee2e2)'; fg = 'var(--dk-red-fg, #b91c1c)'; bd = 'var(--dk-red-line, #fecaca)'; }
|
|
1158
1384
|
} else if (r.error) { fg = 'var(--dk-red-fg, #b91c1c)'; }
|
|
1159
|
-
const miss = (!r.error &&
|
|
1385
|
+
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
1386
|
const title = r.error ? r.error : ((p.description || `${p.name}${p.unit ? ' (' + p.unit + ')' : ''}`) + (miss ? '\n⚠ ' + miss.text + '\n' + miss.tip : ''));
|
|
1161
1387
|
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
1388
|
<span style="color:var(--dk-muted, #64748b)">${esc(p.name)}</span>
|
|
@@ -1244,7 +1470,8 @@ function _tpFieldPaletteHtml(evalRows, params, currentParamId) {
|
|
|
1244
1470
|
// Aggregations — the wrapper a row/ing field must sit inside.
|
|
1245
1471
|
const aggs = ['SUM', 'AVG', 'MIN', 'MAX', 'COUNT']
|
|
1246
1472
|
.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')
|
|
1473
|
+
+ chip('WHERE', 'WHERE', 'Keep only some rows, e.g. SUM(row.amount) WHERE ing.purity > 0')
|
|
1474
|
+
+ chip('IF()', 'IF()', "IF(test, then, else): a number or text by a condition, e.g. IF([VOC] < 50, 'Low VOC', 'Standard')");
|
|
1248
1475
|
|
|
1249
1476
|
// Row fields — always available.
|
|
1250
1477
|
const rowChips = [
|
|
@@ -1431,7 +1658,7 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1431
1658
|
if (!nm) return;
|
|
1432
1659
|
knownParamNames.add(nm);
|
|
1433
1660
|
const r = otherResults[p.id];
|
|
1434
|
-
if (r &&
|
|
1661
|
+
if (r && _tpHasVal(r.value)) paramValueMap[nm] = r.value;
|
|
1435
1662
|
});
|
|
1436
1663
|
const unknownRefs = _tpScanParamRefs(formula)
|
|
1437
1664
|
.map(r => r.name)
|
|
@@ -1445,7 +1672,11 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1445
1672
|
wrap.innerHTML = `<div style="color:var(--danger);font-size:12.5px"><strong>Can’t compute yet:</strong> ${esc(e.message)}</div>`;
|
|
1446
1673
|
return;
|
|
1447
1674
|
}
|
|
1448
|
-
|
|
1675
|
+
// A text result waits for every value it reads (49w), as in the saved table.
|
|
1676
|
+
const held = _tpIsText(result) && (ingMissingFields.size > 0
|
|
1677
|
+
|| _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))))); }));
|
|
1678
|
+
if (held) result = null;
|
|
1679
|
+
const valueStr = Number.isFinite(result) ? _tpFmtValue(result) : _tpIsText(result) ? result : (result == null || typeof result === 'number' ? '—' : String(result));
|
|
1449
1680
|
const unit = (document.getElementById('tp-unit')?.value || '').trim();
|
|
1450
1681
|
const sourceChip = entityType === 'batch'
|
|
1451
1682
|
? `<span style="color:var(--text-muted);font-size:11px;margin-left:6px">on ${source === 'actual' ? 'actual composition' : 'formula proposal'}</span>`
|
|
@@ -1475,6 +1706,7 @@ function _tpRefreshPreview(entityType, entityId) {
|
|
|
1475
1706
|
${sourceChip}
|
|
1476
1707
|
</div>
|
|
1477
1708
|
<div style="margin-top:5px;color:var(--text-muted);font-size:11.5px">Evaluated over ${evalRows.length} composition row${evalRows.length===1?'':'s'}.</div>
|
|
1709
|
+
${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
1710
|
${missingHtml}
|
|
1479
1711
|
${unknownRefHtml}
|
|
1480
1712
|
`;
|
|
@@ -1531,6 +1763,15 @@ function _tpPresetCatalog() {
|
|
|
1531
1763
|
formula: "100 * SUM(row.amount * ing.solids) / (100 * SUM(row.amount))",
|
|
1532
1764
|
description: 'Same as NV but rescaled to 0–100 if ing.solids is stored as fraction (0–1).',
|
|
1533
1765
|
},
|
|
1766
|
+
// Conditions (49v): IF gives text by a threshold. Each works out its own number, so it
|
|
1767
|
+
// needs no other parameter; change the limits to your own.
|
|
1768
|
+
{
|
|
1769
|
+
group: 'Coatings',
|
|
1770
|
+
name: 'VOC class',
|
|
1771
|
+
unit: '',
|
|
1772
|
+
formula: "IF(1000 * SUM(row.amount * ing.volatileOrganic) / SUM(row.amount * ing.volume) <= 50, 'Low VOC', 'Standard')",
|
|
1773
|
+
description: 'Low VOC at 50 g/L or less, else Standard. Set the limit your market uses. Needs ing.density on every row.',
|
|
1774
|
+
},
|
|
1534
1775
|
// ---- Reactive (js/reactive.js; Jun 27 Oct: an index everywhere, acid counts toward the NCO demand) ----
|
|
1535
1776
|
// ing.epoxy … ing.vinyl are meq/g from each ingredient's Reactive groups (0 when it has none). The formula's
|
|
1536
1777
|
// Composition tab shows the same numbers in its balance strip.
|
|
@@ -1541,6 +1782,13 @@ function _tpPresetCatalog() {
|
|
|
1541
1782
|
formula: '100 * SUM(row.amount * ing.amineH) / SUM(row.amount * ing.epoxy)',
|
|
1542
1783
|
description: 'Amine H equivalents per 100 epoxy equivalents; 100 = stoichiometric. From each ingredient’s Reactive groups (EEW, AHEW).',
|
|
1543
1784
|
},
|
|
1785
|
+
{
|
|
1786
|
+
group: 'Reactive',
|
|
1787
|
+
name: 'Mix ratio check',
|
|
1788
|
+
unit: '',
|
|
1789
|
+
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'))",
|
|
1790
|
+
description: 'On ratio for an amine H : epoxy index of 95 to 105, else which side is off. Same groups as the index.',
|
|
1791
|
+
},
|
|
1544
1792
|
{
|
|
1545
1793
|
group: 'Reactive',
|
|
1546
1794
|
name: 'Isocyanate index',
|
|
@@ -1605,6 +1853,13 @@ function _tpPresetCatalog() {
|
|
|
1605
1853
|
formula: "SUM(row.amount * ing.hlb WHERE ing.hlb) / SUM(row.amount WHERE ing.hlb)",
|
|
1606
1854
|
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
1855
|
},
|
|
1856
|
+
{
|
|
1857
|
+
group: 'Surfactants',
|
|
1858
|
+
name: 'Emulsion type',
|
|
1859
|
+
unit: '',
|
|
1860
|
+
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'))",
|
|
1861
|
+
description: 'What the blend HLB favors: 3 to 6 water in oil, 8 to 18 oil in water. Needs ing.hlb.',
|
|
1862
|
+
},
|
|
1608
1863
|
// ---- Food & nutrition ----
|
|
1609
1864
|
// Per 100 g of product: Σ(row wt% × ingredient value per 100 g) / Σ(row wt%).
|
|
1610
1865
|
// Dividing by SUM(row.amount), not 100, keeps it right when the rows don't
|
|
@@ -1665,6 +1920,27 @@ function _tpPresetCatalog() {
|
|
|
1665
1920
|
formula: '2.5 * SUM(row.amount * ing.sodium) / SUM(row.amount) / 1000',
|
|
1666
1921
|
description: 'Salt equivalent as on EU labels: sodium × 2.5, in g/100g. Needs ing.sodium in mg/100g.',
|
|
1667
1922
|
},
|
|
1923
|
+
{
|
|
1924
|
+
group: 'Food & nutrition',
|
|
1925
|
+
name: 'Sugar claim',
|
|
1926
|
+
unit: '',
|
|
1927
|
+
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'))",
|
|
1928
|
+
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.',
|
|
1929
|
+
},
|
|
1930
|
+
{
|
|
1931
|
+
group: 'Food & nutrition',
|
|
1932
|
+
name: 'Salt claim',
|
|
1933
|
+
unit: '',
|
|
1934
|
+
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')))",
|
|
1935
|
+
description: 'EU limits by sodium: 5, 40 and 120 mg/100g for salt free, very low and low. Needs ing.sodium in mg/100g.',
|
|
1936
|
+
},
|
|
1937
|
+
{
|
|
1938
|
+
group: 'Food & nutrition',
|
|
1939
|
+
name: 'Protein claim',
|
|
1940
|
+
unit: '',
|
|
1941
|
+
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'))",
|
|
1942
|
+
description: 'EU: high protein when protein gives 20% of the energy, source of protein at 12%. Needs ing.protein, ing.carb and ing.fat.',
|
|
1943
|
+
},
|
|
1668
1944
|
// ---- General ----
|
|
1669
1945
|
{
|
|
1670
1946
|
group: 'General',
|